當我的函數被賦予一個接口參數作為指針時,我想將指針更新到其他內容(a* = b*)。如果函數參數不是接口,而是指針,則此方法工作正常。給定以下代碼:package mainimport "fmt"type demoInterface interface { GetName() string}type demoStruct struct { name string}func (d demoStruct ) GetName() string { return d.name}func Update(d1 demoInterface) { fmt.Println(d1) d2 := demoStruct{name: "bob"} d1 = &d2 fmt.Println(d1)}func main() { d1 := &demoStruct{name: "frank"} fmt.Println(d1) Update(d1) fmt.Println(d1)}輸出為&{frank}&{frank}&{bob}&{frank}然而,我實際上期望&{frank}&{frank}&{bob}&{bob}如果我替換 Update 函數簽名以接受 *demoStruct 而不是 demoInterface,它將按預期工作。當函數簽名是接口而不是指針時,有沒有辦法讓它按預期工作。
1 回答

慕姐4208626
TA貢獻1852條經驗 獲得超7個贊
如果您確實需要它,則可能是指向接口的指針可能有意義的罕見情況之一。下面是用它修改的示例:
package main
import "fmt"
type demoInterface interface {
GetName() string
}
type demoStruct struct {
name string
}
func (d demoStruct ) GetName() string {
return d.name
}
func Update(d1 *demoInterface) {
fmt.Println(*d1)
d2 := demoStruct{name: "bob"}
*d1 = d2
fmt.Println(*d1)
}
func main() {
d1 := demoInterface(demoStruct{name: "frank"})
fmt.Println(d1)
Update(&d1)
fmt.Println(d1)
}
請注意,由于 take ,我們不能只是傳入(Go 沒有類型協方差),因此我們必須首先將結構轉換為接口。Update*demoInterface*demoStruct
- 1 回答
- 0 關注
- 117 瀏覽
添加回答
舉報
0/150
提交
取消