有指標接收器的Golang 方法[重複]
問題:
在Go中,當建立帶有指標接收器的方法並實現介面時,可能會出現以下錯誤發生:
cannot use obj (type Implementation) as type IFace in return argument: Implementation does not implement IFace (GetSomeField method has pointer receiver)
答案:
要解決此錯誤,請確保指向結構的指標實作該介面。這允許該方法在不建立副本的情況下修改實際實例的欄位。
程式碼修改:
將有問題的行替換為:
return &obj
解釋:
解釋:解釋:
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()) }透過傳回一個指向struct,它實作接口,同時允許方法修改實際實例。 範例(已修改):透過使用指針接收器並確保指針實現了接口,您可以在實現所需方法的同時成功修改結構體的實際實例。
以上是為什麼我的帶有指標接收器的 Go 方法無法實作介面?的詳細內容。更多資訊請關注PHP中文網其他相關文章!