首頁 > 後端開發 > Golang > 主體

Golang 指針混淆,如何從函數取得指針,然後傳遞給修改函數

WBOY
發布: 2024-02-06 10:39:03
轉載
559 人瀏覽過

Golang 指针混淆,如何从函数获取指针,然后传递给修改函数

問題內容

我想使用函式庫(golang walk聲明式),它希望我傳遞一個指標變量,並且函式庫稍後將用一個實例填充它。

出於簿記目的,我嘗試建立一個函數來傳回參考並進一步傳遞它,但在原始函數中我沒有取回對正確物件的參考。

我試圖簡化問題,但我仍然無法正確解決問題,如何在不修改設定函數的情況下,在 test_ref 結構內將值世界填入地圖中。

工作程式碼

<code>var t *walk.LineEdit
...
                    LineEdit{
                        AssignTo: &t,
                    },
</code>
登入後複製

我的嘗試

LineEdit{
                        AssignTo: GetLineEdit("msg"),
                    },
...
func GetLineEdit(name string) **walk.LineEdit {
登入後複製

測試程式碼

type test_ref struct {
    v map[string]*string
}

func (t *test_ref) init() {
    t.v = map[string]*string{}
}

func (t *test_ref) return_ref() **string {
    s := "hello"
    t.v["a"] = &s
    p := t.v["a"]
    return &p
}

type test_setup struct {
    s **string
}

//dont modify this function
func setup(t test_setup) {
    w := "world"
    *(t.s) = &w
}

func main() {
    tr := test_ref{}
    tr.init()
    s := tr.return_ref()
    setup(test_setup{
        s: s,
    })
    fmt.Println(*tr.v["a"])//logging hello

}
登入後複製

如果我對設定函數進行小修改,我可以讓它工作,但由於我不想更新步行庫,我想知道是否有一種方法可以在不觸及設定函數的情況下完成此操作。 < /p>

<code>func setup(t test_setup) {
    w := "world"
    **(t.s) = w
}
</code>
登入後複製


正確答案


#這裡:

func (t *test_ref) return_ref() **string {
    s := "hello"
    t.v["a"] = &s
    p := t.v["a"]
    return &p
}
登入後複製

您回傳的是變數p的位址。

我認為這就是您正在嘗試做的事情:

func (t *test_ref) return_ref() *string {
    s := "hello"
    t.v["a"] = &s
    return &s
}
登入後複製

上面將傳回s的位址,這是儲存在地圖中的內容。然後:

第823章

這會將字串的值設為「world」。

您可以進一步深造並執行以下操作:

type test_ref struct {
    v map[string]**string
}

func (t *test_ref) init() {
    t.v = map[string]**string{}
}

func (t *test_ref) return_ref() **string {
    s := "hello"
    k := &s
    t.v["a"] = &k
    return &k
}

type test_setup struct {
    s **string
}

// dont modify this function
func setup(t test_setup) {
    w := "world"
    *(t.s) = &w
}

func main() {
    tr := test_ref{}
    tr.init()
    s := tr.return_ref()
    setup(test_setup{
        s: s,
    })
    fmt.Println(**tr.v["a"]) //logging hello

}
登入後複製

以上是Golang 指針混淆,如何從函數取得指針,然後傳遞給修改函數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!