Go:Go Pointers and Pass-by-Reference (* and &)
Go•Pointers

Go Pointers and Pass-by-Reference (* and &)

Go has pointers to control memory without pointer arithmetic, keeping memory access safe.

Syntax

ptr := &val *ptr = 100

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
&Address-of OperatorReturns memory address of variable.
*Dereference OperatorReads or writes value stored at pointer.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Go locally:

package main

import "fmt"

// Mutates integer at memory address
func increment(valPtr *int) {
    *valPtr = *valPtr + 1
}

func main() {
    count := 41
    ptr := &count

    fmt.Printf("Initial Count:      %d\n", count)
    fmt.Printf("Memory Address:     %p\n", ptr)

    // Call function with pointer
    increment(&count)
    fmt.Printf("Count after inc:    %d\n", count)
}
Expected Output:
Initial Count:      41
Memory Address:     [address]
Count after inc:    42

How It Works: Step-by-Step

  • Lines 6-8: increment dereferences valPtr and updates caller variable.
  • Line 17: Passes address &count to function.

Key Concepts

  • Go passes arguments by value; passing pointers allows functions to mutate caller state.
  • Go does NOT allow pointer arithmetic (unlike C/C++), preventing memory buffer overflows.
  • nil is the zero value for pointers.

Common Mistake: Dereferencing a nil pointer

Dereferencing a nil pointer causes a runtime panic.

❌ Incorrect
var p *int
*p = 10 // Panic: runtime error: invalid memory address or nil pointer dereference
✅ Correct
val := 0; p := &val; *p = 10

Related Go Tutorials & Compiler

Run and test Go on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Go Online Compiler