Menu

If Go Passes Everything by Value, How Do Pointers Change Anything?
📰

If Go Passes Everything by Value, How Do Pointers Change Anything?

#hackernoon#technology#account#value#pointer
Long article (709 words) — no AI summary yet.
Reading 0:00
15s threshold

Pointers and method receivers can be confusing when you are learning Go. A common question is: if Go passes arguments by value, how can a method change a struct?

The short answer is that a pointer is also a value. Passing a pointer copies the pointer, not the data it points to. The original pointer and the copy can both refer to the same value.

Go passes arguments by value

Consider a function that accepts a struct:

package main

import "fmt"

type Counter struct { Value int }

func increment(c Counter) { c.Value++ }

func main() { counter := Counter{Value: 1} increment(counter)

fmt.Println(counter.Value) // 1 }

When increment is called, Go copies counter into the parameter c .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.