As shown below, I create instance and add to slice. I want to keep memory address of instance but, it is not.
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
}
I know it is possible if I use pointer and slice of pointers.
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
}
However, I want to make ps1 and ps2 as type of []Person because of the parameter types of the methods that will follow(not here). Is there any way?
CodePudding user response:
Each variable defined in a Go program occupies a unique memory location. It is not possible to create a Go program where two variables share the same storage location in memory. It is possible to create two variables whose contents point to the same storage location, but that is not the same thing as two variables who share the same storage location.
So in short, no, if you want ps1[0]
and ps2[0]
to point to the same location in memory, you must use an []*Person
CodePudding user response:
No, you can't. A slice is a contiguous block of memory. Local variables are allocated to arbitrary available memory addresses. mySlice[0]
and mySlice[1]
will always be in neighboring memory, they can't each point at some random location where different local variables happened to be allocated.
I want to keep memory address of instance
There is no reason in practice to need or want this. If you think you need this, you should review your reasoning and determine what you actually need.