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
}
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"
}
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
}
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
}
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 π.
Top comments (0)