DEV Community

Cover image for How to get the memory address of a variable in Go or Golang?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

3

How to get the memory address of a variable in Go or Golang?

#go

Originally posted here!

To get the memory address of a variable in Go or Golang, you can use the & symbol (ampersand) followed by the name of the variable you wish to get the memory address of.

TL;DR

package main

import "fmt"

func main(){

    // a simple variable
    role := "Admin"

    // get the memory address of
    // the `role` variable
    // using the `&` symbol before
    // the `role` variable
    roleMemAddr := &role

    // log to the console
    fmt.Println(roleMemAddr) // 0xc000098050 <- this was the memory address in my system, yours may be different
}
Enter fullscreen mode Exit fullscreen mode

For example, let's say we have a variable called role having a string type value of Admin like this,

package main

func main(){
    // a simple variable
    role := "Admin"
}
Enter fullscreen mode Exit fullscreen mode

Now to get the memory address of the role variable you can use the & symbol followed by the variable name role without any whitespace.

It can be done like this,

package main

func main(){
    // a simple variable
    role := "Admin"

    // get the memory address of
    // the `role` variable
    // using the `&` symbol before
    // the `role` variable
    roleMemAddr := &role
}
Enter fullscreen mode Exit fullscreen mode

Finally, let's print the roleMemAddr value to the console like this,

package main

import "fmt"

func main(){
    // a simple variable
    role := "Admin"

    // get the memory address of
    // the `role` variable
    // using the `&` symbol before
    // the `role` variable
    roleMemAddr := &role

    // log to the console
    fmt.Println(roleMemAddr) // 0xc000098050 <- this was the memory address in my system, yours may be different
}
Enter fullscreen mode Exit fullscreen mode

We have successfully got the memory address of a variable in Go. Yay 🥳!

See the above code live in The Go Playground.

That's all 😃.

Feel free to share if you found this useful 😃.


Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

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

Okay