I have this piece of code
package main
import (
"fmt"
)
func Extend(slice []int, element int) []int {
n := len(slice)
if n == cap(slice) {
// Slice is full; must grow.
// We double its size and add 1, so if the size is zero we still grow.
newSlice := make([]int, len(slice), 2*len(slice)+1)
copy(newSlice, slice)
slice = newSlice
}
slice = slice[0 : n+1]
slice[n] = element
return slice
}
func main() {
slice := make([]int, 0, 5)
for i := 0; i < 10; i++ {
slice = Extend(slice, i)
fmt.Printf("len=%d cap=%d slice=%v\n", len(slice), cap(slice), slice)
fmt.Println("address of 0th element:", &slice[0])
fmt.Println("address of slice:", &slice) // why does this print the slice and not its address?
fmt.Printf("address of slice: %p\n", &slice) // why is this different from below? and why does it not change when a new slice is created pointing to a different array?
fmt.Printf("address of slice: %p\n\n", slice)
}
}
My question on the second Println at the bottom in the loop. If you run it, you will see it prints out &[values...]. Why does it not print out the address? I know you can do it with Printf, among other ways, and it works, but what about Println? Println with &slice[0] works fine, it prints the address not the value, but Println with &slice is just like nope.
I also just noticed that when I do the Printf statement %p with &slice, vs then I do only slice, I get different addresses. Why? And the address with &slice does not change when it is changed (run it, the program resizes the array and creates a new slice). But printf(%p, slice) does change?