在创建一个这样的结构:
type Foo struct { name string } func (f Foo) SetName(name string){ f.name=name } func (f Foo) GetName string (){ return f.name }
p:=new(Foo) p.SetName("Abc") name:=p.GetName() fmt.Println(name)
评论(和工作)示例:
原文链接:https://www.f2er.com/go/187899.htmlpackage main import "fmt" type Foo struct { name string } // SetName receives a pointer to Foo so it can modify it. func (f *Foo) SetName(name string) { f.name = name } // Name receives a copy of Foo since it doesn't need to modify it. func (f Foo) Name() string { return f.name } func main() { // Notice the Foo{}. The new(Foo) was just a syntactic sugar for &Foo{} // and we don't need a pointer to the Foo,so I replaced it. // Not relevant to the problem,though. p := Foo{} p.SetName("Abc") name := p.Name() fmt.Println(name) }
Test it并采取A Tour of Go以了解更多关于方法和指针,以及Go的基本知识。