Golang Pointers Challenge: Understanding References

GoGoBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

This challenge will test your understanding of pointers in Golang. Pointers are used to pass references to values and records within your program.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Go`")) -.-> go/DataTypesandStructuresGroup(["`Data Types and Structures`"]) go/DataTypesandStructuresGroup -.-> go/pointers("`Pointers`") subgraph Lab Skills go/pointers -.-> lab-15414{{"`Golang Pointers Challenge: Understanding References`"}} end

Pointers

The problem is to understand how pointers work in contrast to values with two functions: zeroval and zeroptr. zeroval has 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, meaning that it takes an int pointer. The *iptr 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.

Requirements

  • You should have a basic understanding of Golang.
  • You should know how to define and use functions in Golang.
  • You should know how to use pointers in Golang.

Example

## `zeroval` doesn't change the `i` in `main`, but
## `zeroptr` does because it has a reference to
## the memory address for that variable.
$ go run pointers.go
initial: 1
zeroval: 1
zeroptr: 0
pointer: 0x42131100

Summary

In this challenge, you learned how to use pointers in Golang. You also learned the difference between passing values and pointers to functions.

Other Go Tutorials you may like