首页 > GO语言中请问为什么不能直接访问一个Strut的方法?

GO语言中请问为什么不能直接访问一个Strut的方法?

func main() {
    t := test // 如果这里改成 t:=new(test)就可以执行了
    t.Name = "ACE"
    t.test()
}

type test struct {
    Name string
}

func (this test) test() {
    fmt.Println(this.Name)
}

为什么这样写会报错?
command-line-arguments
./main.go:14: type test is not an expression
是因为没有实例化的原因么?如果不用new(不实例化), 怎么直接能调用到test?


t := test{}

这样就可以了,初始化一个对象是用 xxx{}


使用的不是指针,改成:

func (this *test) test() {
    fmt.Println(this.Name)
}

再试试


t := test
t是什么?一种类型? test的别名?
你要的是一个test类型的变量。
这里是写错了。这是:=的锅,你用var定义一下就没有问题。

【热门文章】
【热门文章】