這似乎是相當基本的,但我無法輕易糾正下面的程序 https://play.golang.org/p/8IJn7g0m1Asimport ( "fmt")type A struct{ value int }type B *Afunc (b B) Print() { fmt.Printf("Value: %d\n", b.value)}func main() { a := &A{1} b := new(B(a)) b.Print()}./prog.go:10:6: invalid receiver type B (B is a pointer type)./prog.go:16:12: B(a) is not a type首先,我嘗試將接收器更改為 ,但不起作用。對于第二個,我嘗試了,這也不起作用。func (b *B) &B{a}A實際上是一個包含互斥體的復雜結構(由 生成的結構),所以我需要將其保留為指針,同時需要在其上定義其他方法,因此定義一個新類型。protobufB
2 回答

小怪獸愛吃肉
TA貢獻1852條經驗 獲得超1個贊
您需要在 B 的結構中嵌入 A。不能使用指針聲明新類型。
type A struct{ value int }
type B struct{
*A
}
func (b B) Print() {
fmt.Printf("Value: %d\n", b.value)
}
func main() {
a := &A{1}
b := B{a}
b.Print()
}
- 2 回答
- 0 關注
- 143 瀏覽
添加回答
舉報
0/150
提交
取消