如下所示,我创建实例并添加到切片中。我想保留实例的内存地址,但事实并非如此。
type Person struct {
name string
}
func main() {
p := Person{name: "foo"}
ps1 := []Person{p}
ps2 := []Person{p}
fmt.Printf("%p\n", &p) // 0xc000010250
fmt.Printf("%p\n", &ps1[0]) // 0xc000010260
fmt.Printf("%p\n", &ps2[0]) // 0xc000010270
}
我知道如果我使用指针和指针切片是可能的。
type Person struct {
name string
}
func main() {
p := Person{name: "foo"}
ps1 := []*Person{&p}
ps2 := []*Person{&p}
fmt.Printf("%p\n", &p) // 0xc00010a210
fmt.Printf("%p\n", ps1[0]) // 0xc00010a210
fmt.Printf("%p\n", ps2[0]) // 0xc00010a210
}
但是,我想将 ps1 和 ps2 作为 []Person 的类型,因为将遵循的方法的参数类型(不在这里)。有什么办法吗?
慕村225694
qq_笑_17
相关分类