Home
Go
Pointer and Address Type Example
Updated Jan 24, 2025
Dot Net Perls
Pointer. The Go language supports pointers—with a pointer, we store an address of a variable. We can then use the pointer to get the variable's value.
Operators. To get the value of a variable from a pointer, we use the pointer indirection (star) operator. To create a pointer, we use the address operator.
new
Example. This example uses a pointer to a string in a struct. Because Go has garbage collection, we can use pointers to variables without worrying about when to free variables from memory.
struct
Part 1 We use a string pointer in a struct. The pointer is a value that stores the address of a string variable.
Part 2 A func can receive a pointer. To get the value from the pointer, we use the "*" pointer indirection operator.
Part 3 We initialize a struct that has a pointer within it. We use the address operator to set the value of the pointer field "x".
Part 4 With Println, we see that the pointer holds an address value. When we use the "*" operator we see the actual string value.
fmt
Part 5 It is possible to call a method that receives a pointer—we can use the address operator of a variable, or use an existing pointer.
package main import "fmt" // Part 1: use a pointer to string as a field in a struct. type Test struct { x *string } func Example(x *string) { // Part 2: receive a pointer as an argument, and access its value with pointer indirection. fmt.Println("func Example", *x) } func main() { // Part 3: create a string, and use the address operator to initialize a pointer in a struct. v := "bird" t := Test{x: &v} // Part 4: print the address of the string pointer, and also its value. fmt.Println(" t", t) fmt.Println(" t.x", t.x) fmt.Println("*t.x", *t.x) // Part 5: pass a string pointer to a method. Example(&v) Example(t.x) }
t {0xc0000220a0} t.x 0xc0000220a0 *t.x bird func Example bird func Example bird
Go supports pointers, but because it has garbage collection, we do not need to worry about the pointers becoming invalid or being freed from memory when they are still needed.
The syntax for Go pointers is similar to (or the same as) languages like C. We cannot use arithmetic on pointers, as this would not work well with the garbage collector.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 24, 2025 (edit link).
Home
Changes
© 2007-2025 Sam Allen