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

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

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.

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay