创建这样的结构后:
type Foo struct {
name string
}
func (f Foo) SetName(name string) {
f.name = name
}
func (f Foo) GetName() string {
return f.name
}
如何创建 Foo 的新实例并设置和获取名称?
我尝试了以下方法:
p := new(Foo)
p.SetName("Abc")
name := p.GetName()
fmt.Println(name)
没有打印任何内容,因为 name 为空。那么如何设置和获取结构体中的字段呢?
工作游乐场
评论(和工作)示例:
package 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并采取围棋之旅了解有关方法和指针的更多信息,以及 Go 的基础知识。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)