When you use indexer on array or slice in return you get the variable so you can take an address of it. I wonder how it is possible because the array/slice could more nested than the target variable:
// ptr declaration here
{
// array declaration here
ptr = &array[0];
}
In array case I see a problem that the data are on stack, with slice, that allocating it on heap does not solve automatically the problem, because GC could remove entire slice unless taking an address of the element links to the slice itself (thus preventing freeing memory).
Example: what happens when there is no guarantee on validity of the pointers -- let's say my array is a collection of colors. I pick one element, take an address of it, entire array is deleted (because it went of out scope), I check the value of element and it is 3.14. Or "hello world". Or maybe green
. Since there is no guarantee it could be anything that is located at given address.
The Go compiler and the Go garbage collector guarantee that memory is not freed until it is no longer used.
To learn the basics of garbage collection, the Go team recommends The Garbage Collection Handbook: The Art of Automatic Memory Management.
See The Go Blog: Getting to Go: The Journey of Go's Garbage Collector for some history.