DEV Community

Teruo Kunihiro
Teruo Kunihiro

Posted on

10

Summary of pointer of Golang

#go

Sometimes I confuse how to retrieve from pointer variable. So I wanna summary the pointer of Golang not to forget them.
Because I haven't used languages which have pointer variable.

Then it's just memo for me.

  • & stands for the memory address of value.
  • * (in front of values) stands for the pointer's underlying value
  • * (in front of types name) stands for to store an address of another variable

It's an example

package main

import "fmt"

type H struct {
    id *int
}

func main() {
    a := 10

    p := &a
    fmt.Println(p)  //0x10410020
    fmt.Println(*p) //10

    a = 11
    fmt.Println(p)  //0x10410020
    fmt.Println(*p)

    q := 90
    b := H{id: &q}
    fmt.Println(b.id)   //0x1041002c
    fmt.Println(*b.id)  //90

    q = 80
    fmt.Println(b.id)   //0x1041002c
    fmt.Println(*b.id)  //80
}
Enter fullscreen mode Exit fullscreen mode

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (4)

Collapse
 
der_gopher profile image
Alex Pliutau

Another way to get a pointer is to use the built-in new function:

func one(xPtr *int) {
  *xPtr = 1
}
func main() {
  xPtr := new(int)
  one(xPtr)
  fmt.Println(*xPtr) // x is 1
}

new takes a type as an argument, allocates enough memory to fit a value of that type and returns a pointer to it.

Collapse
 
sirbowen78 profile image
sirbowen78

Concise and easy to understand summary, thank you for sharing :)

Collapse
 
llitfkitfk profile image
田浩
Collapse
 
yeboahnanaosei profile image
Nana Yeboah

Thank you so much my friend. This is exactly what I needed.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up