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

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

帶有指針接收器的 Golang 方法

帶有指針接收器的 Golang 方法

Go
郎朗坤 2021-11-22 19:36:39
我有這個示例代碼package mainimport (    "fmt")type IFace interface {    SetSomeField(newValue string)    GetSomeField() string}type Implementation struct {    someField string}func (i Implementation) GetSomeField() string {    return i.someField}func (i Implementation) SetSomeField(newValue string) {    i.someField = newValue}func Create() IFace {    obj := Implementation{someField: "Hello"}    return obj // <= Offending line}func main() {    a := Create()    a.SetSomeField("World")    fmt.Println(a.GetSomeField())}SetSomeField 不能按預期工作,因為它的接收器不是指針類型。如果我將方法更改為指針接收器,我希望可以工作,它看起來像這樣:func (i *Implementation) SetSomeField(newValue string) { ...編譯這會導致以下錯誤:prog.go:26: cannot use obj (type Implementation) as type IFace in return argument:Implementation does not implement IFace (GetSomeField method has pointer receiver)如何在不創建副本的情況下struct實現接口和方法SetSomeField更改實際實例的值?這是一個可破解的片段:https : //play.golang.org/p/ghW0mk0IuU我已經在 go (golang) 中看到了這個問題,如何將接口指針轉換為結構指針?,但我看不出它與這個例子有什么關系。
查看完整描述

2 回答

?
慕俠2389804

TA貢獻1719條經驗 獲得超6個贊

您指向結構的指針應該實現接口。通過這種方式,您可以修改其字段。


看看我是如何修改你的代碼的,讓它按你的預期工作:


package main


import (

    "fmt"

)


type IFace interface {

    SetSomeField(newValue string)

    GetSomeField() string

}


type Implementation struct {

    someField string

}    


func (i *Implementation) GetSomeField() string {

    return i.someField

}


func (i *Implementation) SetSomeField(newValue string) {

    i.someField = newValue

}


func Create() *Implementation {

    return &Implementation{someField: "Hello"}

}


func main() {

    var a IFace

    a = Create()

    a.SetSomeField("World")

    fmt.Println(a.GetSomeField())

}


查看完整回答
反對 回復 2021-11-22
?
天涯盡頭無女友

TA貢獻1831條經驗 獲得超9個贊

簡單的答案是,您將無法在以SetSomeField您想要的方式工作的同時讓結構實現您的接口。

但是,指向結構的指針將實現接口,因此更改您的Create方法 doreturn &obj應該可以使事情正常工作。

潛在的問題是您修改后的SetSomeField方法不再在Implementation. 雖然該類型*Implementation將繼承非指針接收器方法,但反之則不然。

其原因與指定接口變量的方式有關:訪問存儲在接口變量中的動態值的唯一方法是復制它。例如,想象以下內容:

var impl Implementation
var iface IFace = &impl

在這種情況下,調用可以iface.SetSomeField工作,因為它可以復制指針以用作方法調用中的接收者。如果我們直接在接口變量中存儲一個結構體,我們需要創建一個指向該結構體的指針來完成方法調用。一旦創建了這樣的指針,就可以訪問(并可能修改)接口變量的動態值而無需復制它。


查看完整回答
反對 回復 2021-11-22
  • 2 回答
  • 0 關注
  • 263 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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