How to Print the Memory Address of a Variable in Go
In this article, you’ll learn different ways to print the memory address of a variable in Go. This is useful when you want to find out the location in memory of a variable perhaps in order to compare it to something else when debugging your code.
The easiest way to print the memory address of a variable is to pass a pointer
to the variable to the fmt.Println()
method:
func main() {
a := 2
fmt.Println(&a)
}
0xc0000b6000
When using a print formatted method (like fmt.Printf()
), you may use the
%p
verb to obtain the address of a variable like this:
func main() {
a := 2
fmt.Printf("The address of a is: %p\n", &a)
}
The address of a is: 0xc0000b6000
The above methods work for variables of any data type:
func main() {
a := 2
b := "a string"
c := map[string]int{
"a": 1,
}
d := struct {
name string
age int
}{
"John", 20,
}
e := true
f := func() {
fmt.Println("hello world")
}
g := &f
h := []int{1, 2, 3}
i := h[0]
fmt.Printf("The address of a is: %p\n", &a)
fmt.Printf("The address of b is: %p\n", &b)
fmt.Printf("The address of c is: %p\n", &c)
fmt.Printf("The address of d is: %p\n", &d)
fmt.Printf("The address of e is: %p\n", &e)
fmt.Printf("The address of f is: %p\n", &f)
fmt.Printf("The address of g is: %p\n", &g)
fmt.Printf("The address of h is: %p\n", &h)
fmt.Printf("The address of i is: %p\n", &i)
}
The address of a is: 0xc00001a0e0
The address of b is: 0xc000010250
The address of c is: 0xc00000e028
The address of d is: 0xc00000c030
The address of e is: 0xc00001a0e8
The address of g is: 0xc000120018
The address of h is: 0xc00001a0e0
The address of i is: 0xc0000b6000
But note that you cannot take the address of a literal, map value, or function return value. The compiler will show an error if you attempt to do so:
func main() {
f := func() string {
return "hello world"
}
fmt.Printf("The address of f() is: %p\n", &f())
}
./main.go:12:45: invalid operation: cannot take address of f() (value of type string)
Removing the 0x prefix from the memory address
The 0x
prefix in a memory address is used to indicate that the address is in
hexadecimal form. If you’d like to print the memory address of a variable
without the 0x
prefix, use the %#p
verb as shown below:
func main() {
a := 1
fmt.Printf("The address of a is: %p\n", &a)
fmt.Printf("The address of a is: %#p\n", &a)
}
The address of a is: 0xc00001a0e0
The address of a is: c00001a0e0
Comparing memory address values
The ==
operator can be used to compare memory addresses in Go:
func main() {
a := 1
b := &a
c := b
fmt.Println(&a == c)
}
true
Thanks for reading, and happy coding!