-1

In Go, everything is pass by value. Calling a function with a value results in the value being copied and function only accessing the copy of the value.

Pointer semantics allow something passed "by value" a way in which to update the "original" value, just as if we would have passed a pointer to it.

What types have pointer semantics?

kostix
  • 51,517
  • 14
  • 93
  • 176
Zam
  • 1,121
  • 10
  • 27
  • Each and every type needs a pointer to hav its _own_ value be modified. This question makes no sense and just because slices et al. have reference _semantics_ on their _elements_ doesn't mean they (the slice) can be changed without a pointer. – Volker May 16 '23 at 12:34
  • 6
    The question is misleading. Everything you pass a copy is made. You can't modify the original value. The question should rather be what values have "pointer schematics", see [What do "value semantics’" and "pointer semantics" mean in Go?](https://stackoverflow.com/questions/51264339/what-do-value-semantics-and-pointer-semantics-mean-in-go/51265000#51265000) – icza May 16 '23 at 12:35
  • 1
    [My take on this](https://stackoverflow.com/a/20856597/720999) which is slightly different from icza's but basically tries to explain the same concepts. The question is indeed misleading, but I beleive this is an honest mistake. – kostix May 16 '23 at 12:59
  • 1
    Also [this answer](https://stackoverflow.com/a/72979409/720999), while mostly deals with slices of values vs slices of pointers to values, also touches upon reference semantics of certain types. – kostix May 16 '23 at 13:06

1 Answers1

2

Variables of all types require the use of a pointer, if you wish to modify the value passed to a function.

The only exception is that some reference types may have their members modified without passing a pointer, but the type value cannot be modified without using a pointer.

Example of modifying a slice member (but not the slice itself) (playground):

func main() {
    s := []int{1, 2, 3, 4}
    modifySliceMember(s)
    fmt.Println(s) // [90 2 3 4]
}

func modifySliceMember(s []int) {
    if len(s) > 0 {
        s[0] = 99
    }
}

To modify the slice itself (playground):

func main() {
    s := []int{1, 2, 3, 4}
    modifySlice(&s)
    fmt.Println(s) // []
}

func modifySlice(s *[]int) {
    *s = make([]int, 0)
}

However, note that even in this case, we're not really changing the passed value strictly speaking. The passed value in this case is a pointer, and that pointer cannot be changed.

Zam
  • 1,121
  • 10
  • 27
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189