考虑一个简单的示例程序。 structAPtr 嵌入指针,structAVal 直接嵌入struct structB:
package main
import "fmt"
type structB struct {
foo int
}
type structAPtr struct {
bar *structB
}
type structAVal struct {
bar structB
}
func main() {
// referencing bStruct
b1 := structB{foo: 12}
aPtr := structAPtr{bar: &b1}
fmt.Println("Before assignment:")
fmt.Printf("aPtr.bar.foo = %d, b.foo = %d\n", aPtr.bar.foo, b1.foo)
aPtr.bar.foo = 42
fmt.Println("After assignment:")
fmt.Printf("aPtr.bar.foo = %d, b.foo = %d\n", aPtr.bar.foo, b1.foo)
// copying bStruct
b2 := structB{foo: 12}
aVal := structAVal{bar: b2}
fmt.Println("Before assignment:")
fmt.Printf("aVal.bar.foo = %d, b.foo = %d\n", aVal.bar.foo, b2.foo)
aVal.bar.foo = 42
fmt.Println("After assignment:")
fmt.Printf("aVal.bar.foo = %d, b.foo = %d\n", aVal.bar.foo, b2.foo)
}
int structB.foo 用于演示在structAPtr 或structAVal 内部操作时structB 是否发生变化。
这个程序输出:
Before assignment:
aPtr.bar.foo = 12, b.foo = 12
After assignment:
aPtr.bar.foo = 42, b.foo = 42 <------------ both changed
Before assignment:
aVal.bar.foo = 12, b.foo = 12
After assignment:
aVal.bar.foo = 42, b.foo = 12 <------------ only assignee changed
查看结果显示:
编辑:
如果您的structB 无论如何都只有指针接收器,那么预期的行为可能是更改strucA 中的structB 会同时更新它们。这是我的示例中的场景 1,并且肯定需要一个指针。来自围棋之旅:
带有指针接收器的方法可以修改接收器指向的值 [...]。由于方法经常需要修改它们的接收器,因此指针接收器比值接收器更常见。
希望有帮助!