Golang Tutorials

Pointer and Slices

This is a basic pointer slicer relationship guide. Visit the Pointer Basics for basic pointer examples.

Fresh Main.Go

package main

func main() {
    // blank slate
}

Next we are going to add a variable assignment and fmt.Printf().

package main

import "fmt"

func main() {
	mySlice := []string{"Hello", "HouseCat"}
	fmt.Println(mySlice)

	modSlice(mySlice)

	fmt.Println(mySlice)
}

func modSlice(s []string) {
	s[0] = "GoodBye"
}

Output

[Hello HouseCat how are you?]
[GoodBye HouseCat how are you?]

Why did this work?

Why this did work!

The value is really changed because in golang, a slice contains a pointer to the head of the string array, knowing the length of the slice, you essentially pass the entire memory address range for the slice into the function.

This can look a little confusing, but let's do a thought experiment. Imagine that you just passed in a struct that had a pointer as a member. If you were to pass this struct to a function, then update the pointer member of the struct (by dereference and value assignment) it would change both in the local function and main. It's slightly more complicated for golang slice but you should keep this imagery in your head to understand what is happening.

You are still passing values to the function, it is just that those values are memory addresses.

A slice is a reference type. There are other reference types such as pointers, channels, and maps.

Additional Links

Play.Golang.Org Sandbox

I have embedded this source location for you to run and see outputs.