memory in slice and array
tags: learning go programming
questions to answer
- when a slice is created on top of an array, does it have its own memory?
content
func main() {
i := [3]int{1, 2, 3}
for value := range i {
fmt.Println("addr of element in i is: ", &value)
}
fmt.Println()
j := i[:]
k := i[:]
for value := range j {
fmt.Println("addr of element in j is: ", &value)
}
fmt.Println()
for value := range k {
fmt.Println("addr of element in k is: ", &value)
}
}the output of the above code is:
addr of element in i is: 0x140000a6008
addr of element in i is: 0x140000a6010
addr of element in i is: 0x140000a6018
addr of element in j is: 0x140000a6020
addr of element in j is: 0x140000a6028
addr of element in j is: 0x140000a6030
addr of element in j is: 0x140000a6038
addr of element in j is: 0x140000a6040
addr of element in j is: 0x140000a6048we can see that the address of i is different from the address of j, which is also different from another slice k.
so slice has different memory than its underlying array, and slices that reference the same underlying array have different memory
Note
from ^addresses we can see, each
inthas taken up 8 bytes. this can be further check byunsafe.Sizeof
→ https://stackoverflow.com/a/26975872