NASutils Knowledge BaseUnofficialPolski

Go · lesson 17 of 30 · Data, functions and the command linePass an address

A function gets a copy. With & and * it works on the caller's variable.

Programming on the NAS › Go in 30 lessons

17-pointers.go Download 17-pointers.go

package main

import "fmt"

func addByValue(n int) {
	n++ // changes the function's own copy
}

func addByPointer(n *int) {
	*n++ // changes the caller's number
}

func main() {
	count := 1
	addByValue(count)
	fmt.Println("after addByValue:", count)
	addByPointer(&count)
	fmt.Println("after addByPointer:", count)

	var missing *int
	fmt.Println("no address yet:", missing == nil)
}

Terminal

$ ./17-pointers
after addByValue: 1
after addByPointer: 2
no address yet: true

Exercise

Write swap, which exchanges two numbers.

TurboShell does not contain Go. These programs are made in Bucket & Code with its Go runtime; the finished file runs on the NAS without Go.