創建像這樣的結構后: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)沒有打印任何內容,因為名稱為空。那么如何設置結構中的字段?https://play.golang.org/p/_xkIc-n6Wbk
3 回答

墨色風雨
TA貢獻1853條經驗 獲得超6個贊
評論(和工作)示例:
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)
}
測試它并進行Go之旅,以全面了解有關方法和指針以及Go的基礎知識。
- 3 回答
- 0 關注
- 287 瀏覽
添加回答
舉報
0/150
提交
取消