亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在struct方法中設置和獲取字段

如何在struct方法中設置和獲取字段

Go
UYOU 2021-05-11 18:16:35
創建像這樣的結構后: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的基礎知識。


查看完整回答
反對 回復 2021-05-17
  • 3 回答
  • 0 關注
  • 287 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號