看起來很基礎,但我不能輕易糾正下面的程序 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) ,但沒有成功。對于第二個,我嘗試了 like &B{a},但也沒有用。A實際上是一個復雜的結構體,里面有互斥體(由 生成的結構體protobuf),所以我需要把它保存為指針,同時需要在上面定義額外的方法,所以定義一個新的類型B。
2 回答

qq_遁去的一_1
TA貢獻1725條經驗 獲得超8個贊
您需要將 A 嵌入到 B 的結構中。您不能使用指針聲明新類型。
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 關注
- 137 瀏覽
添加回答
舉報
0/150
提交
取消