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

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 😃.


Top comments (0)