Search code examples
goreferenceslice

Is it safe to keep reference, but not assigning data to an actual variable?


I want to keep a list of references in a slice, but I couldn't fine any resource online that explains if keeping reference without assigning to a variable is safe or not?

I mean, is it possible that the OS write something in the referenced addresses that is not expected by the programmer?

Here is an example code:

type ListItem [8]uint64

list := make([]*ListItem, 0)

list = append(list, &ListChunk{})
list = append(list, &ListChunk{})
list = append(list, &ListChunk{})

In other words, is it guaranteed that Items in the slice named list stay same while program is running, no matter how long it takes to run?


Solution

  • in your case probably no (the references will remain unchanged) but it depends also on what your program does to it :

    The Go runtime doesn't change the references (pointers) stored in a slice for the lifetime of the program But in ONE CONDITION: -you don't reassign the slice or its elements pointers (array of [8]uint64) in a function . As long as you don't reassign new values to the elements of the slice, the references will remain unchanged.