Sobes.tech
Junior — Middle

Is it safe to modify the contents of a slice in memory without additional checks?

sobes.tech AI

Answer from AI

In Go, a slice is a structure containing a pointer to an array, a length, and a capacity. Modifying the contents of a slice in memory is possible, but safety depends on the context:

  • If the slice is not shared between goroutines, changing elements is safe without additional checks.
  • If the slice is used concurrently in multiple goroutines, access must be synchronized (e.g., using mutexes), otherwise data races may occur.
  • Changing the length or capacity of a slice (via append) may lead to a new array being allocated, so references to the old array may become invalid.

Thus, it is safe to modify the contents of a slice without additional checks only in a single-threaded environment or when synchronization is guaranteed.

Example of safe modification:

s := []int{1, 2, 3}
s[0] = 10  // safe if there are no competing goroutines

For concurrent access:

var mu sync.Mutex
mu.Lock()
s[0] = 10
mu.Unlock()