Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 147 ยท Pointers and Memory

Pointers, Values and Functions

Go always passes arguments by value. See how pointers let functions modify data, why returning a pointer to a local is safe, and how slices, maps and channels behave as parameters.

Here is one rule that answers most questions about Go function calls: Go always passes by value. When you call a function, every argument is copied into the matching parameter. There is no "pass by reference" mode, no hidden reference parameters, and no exceptions.

That sounds limiting, but it is not, because the value you pass can itself be a pointer. Copying a pointer is cheap, and the copy still points at the original data. This lesson shows how that works, why returning a pointer to a local variable is perfectly safe, when copying a big struct matters, and why slices, maps and channels sometimes seem to behave like references. You should be comfortable with pointers and functions first.

Arguments are copies

Watch what happens when a function tries to change its parameter:

Go Changing a copy has no effect

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The function received its own variable n, initialized with the value of x. Changing n leaves x alone. The same is true for structs and arrays: the whole value is copied.

Go Structs and arrays are copied too

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Modifying the caller's data with a pointer

To let a function change a variable, pass its address. The function receives a copy of the pointer, but both pointers hold the same address, so writing through the copy changes the original.

Go Modify through a pointer parameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Notice that the call site shows the intent: addTen(&x) makes it visible that x may change. That visibility is a deliberate design choice in Go.

The pointer itself is still passed by value. If the function assigns a new address to its parameter (n = &other), the caller's pointer is unchanged. Only writing through the pointer (*n = ...) affects the caller.

Go Reassigning the pointer only changes the copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Returning a pointer to a local variable

In C, returning the address of a local variable is a classic bug, because the stack frame disappears when the function returns. In Go it is safe and common. The compiler notices that the variable outlives the call and allocates it on the heap, and the garbage collector frees it when nobody refers to it any more. This analysis is called escape analysis, covered in Stack, Heap and Escape Analysis.

Go Returning the address of a local is fine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Each call to counter creates a separate c. This is why functions named NewSomething can simply return &Something{...}.

Large values: copy or point?

Copying a struct with three fields costs next to nothing. Copying an array with 100,000 elements on every call does not. When a function takes a large value, you have two choices: pass a pointer, or use a slice (which is only three words wide).

Go Large arrays are copied per call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Do not guess about performance. A copy that fits in a few registers is often faster than following a pointer, and a pointer can force a value onto the heap. Use pointers because you need to modify or share, and measure before using them only for speed.

Slices, maps and channels

Slices, maps and channels are passed by value like everything else. The surprise is what gets copied.

  • A slice value is a small header: pointer to an array, length, and capacity. Copying it copies the header, so the copy still shares the same backing array. Element writes are visible to the caller; append changes the header, which the caller does not see.
  • A map value is a pointer to a runtime structure. The copy refers to the same map, so inserts, updates and deletes are visible to the caller. Assigning a new map to the parameter is not.
  • A channel value is also a handle to shared state. Every copy sends to and receives from the same channel.
Go Slices share elements, not headers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The standard way to grow a slice in a function is to return the new slice and let the caller assign it (the way the built-in append works). A pointer to a slice is sometimes seen, but returning is more idiomatic. The slice internals lesson explains the header in depth.

Go Maps and channels are shared

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Do not conclude that "slices and maps are references". They are values that contain references. The distinction matters in exactly the cases above: reassigning or appending inside a function does not reach back to the caller. A nil map parameter is also dangerous: writing to it panics, and the function cannot fix that for the caller.

Value semantics or pointer semantics?

For a given type, pick one style and stay consistent:

Style Typical types Parameter looks like
Value semantics numbers, strings, time.Time, small structs func f(p Point)
Pointer semantics types with state, mutexes, connections, large structs func f(c *Client)
Reference-like built-ins slices, maps, channels, funcs func f(s []int)

Mixing styles for one type (some functions taking T, some *T) makes code harder to read, and it causes subtle bugs when a value copy of a type that should not be copied slips in. The same consistency rule returns in Value vs Pointer Receivers.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Go passes function arguments:

    Every argument is copied. Slices, maps and channels are copied too, but the copies share underlying data, which gives them reference-like behavior.
  2. 2. What does x hold after func inc(n int) { n++ } and x := 1; inc(x)?

    n is a copy of x. Incrementing the copy does not change x.
  3. 3. Is it valid and safe to write func f() *int { v := 3; return &v }?

    Escape analysis detects that v is still referenced after f returns and allocates it on the heap. The garbage collector frees it later.
  4. 4. After func add(s []int) { s = append(s, 1) } and n := []int{}; add(n), what is len(n)?

    append returned a new slice header that was assigned to the local s. The caller's header is unchanged, so len(n) is still 0.
  5. 5. What happens to the caller when a function receives m map[string]int and runs m["k"] = 1?

    A map value is a handle to shared data, so writes through the copy are visible to the caller. Only assigning a different map to m stays local.

Summary

  • Go passes everything by value: arguments are copies of the caller's values.
  • To let a function modify a variable, pass a pointer. Writing through the pointer changes the original; reassigning the pointer variable does not.
  • Returning a pointer to a local variable is safe, because the compiler moves it to the heap when needed.
  • Large structs and arrays are copied in full on each call; pointers or slices avoid the copy, but measure before optimizing.
  • Slices, maps and channels are small values that refer to shared data. Element and entry changes are visible to the caller; reassigning or appending is not.
  • Choose value or pointer semantics per type and be consistent.

Next: new, make and Composite Literals