0% found this document useful (0 votes)
15 views1 page

Go by Example - Pointers

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views1 page

Go by Example - Pointers

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Go by Example: Pointers https://gobyexample.

com/pointers

Go by Example: Pointers
Go supports pointers, allowing you to pass
references to values and records within your
program.

package main

import "fmt"

We’ll show how pointers work in contrast to values func zeroval(ival int) {
with 2 functions: zeroval and zeroptr. zeroval has ival = 0
an int parameter, so arguments will be passed to }
it by value. zeroval will get a copy of ival distinct
from the one in the calling function.

zeroptr in contrast has an *int parameter, func zeroptr(iptr *int) {


meaning that it takes an int pointer. The *iptr *iptr = 0
code in the function body then dereferences the }
pointer from its memory address to the current
value at that address. Assigning a value to a
dereferenced pointer changes the value at the
referenced address.

func main() {
i := 1
fmt.Println("initial:", i)

zeroval(i)
fmt.Println("zeroval:", i)

The &i syntax gives the memory address of i, i.e. a zeroptr(&i)


pointer to i. fmt.Println("zeroptr:", i)

Pointers can be printed too. fmt.Println("pointer:", &i)


}

zeroval doesn’t change the i in main, but zeroptr $ go run pointers.go


does because it has a reference to the memory initial: 1
address for that variable. zeroval: 1
zeroptr: 0
pointer: 0x42131100

Next example: Strings and Runes.

by Mark McGranaghan and Eli Bendersky | source | license

1 of 1 11/26/24, 23:34

You might also like