Go: Pointers

In this guide I will explain:

  1. What is a pointer?
  2. Access address and value of pointer
  3. New function
  4. Passing pointer to a function

What is a pointer?

A pointer is a variable that points to a memory address of another variable. But it is a special kind of variable it stores the memory address of another variable. In other languages, pointers are disguised as “references,” and there’s not much that can be done with them except pass them around. In Go Pointers are explicitly visible, considered safe because Go does not define the addition operator on the pointer type. They can only be used to reference an existing object.

pointer diagram

How to access memory address of a variable?

& — get address

How to access the value of stored at a memory address?

*- get the value

How to create a pointer?

var age *type — type is the data type

What is the new function?

Instead of creating a new variable to point to a memory address you could use new. When using the new function go stores zero-value of data type passed to the new function and returns memory address of it.

How to pass a pointer to a function?

Passing a pointer to a function is similar to passing a variable to a function, allows a function to modify an object in-place.

What can you do with pointers?

Go provides a pointer type that stores the memory location where data of a specific type is stored. Pointers can be used to pass a struct to a function by reference without creating a copy.

I hope you enjoyed this guide and understand the basic of how pointers work in Go. Please leave comments below and check out the below links.

Go Project Structure:https://medium.com/@tommarler/go-project-structure-f74d34b587dc

Go Types: https://medium.com/@tommarler/go-types-be944f1473ff

Go Rest Calls and JSON: https://medium.com/@tommarler/go-json-13880dc1f1f8

Go XML and SEO: https://medium.com/@tommarler/go-xml-and-seo-4adc5226d606