26. Pointers

Sharing!

Pointers

Pointers is is type of variable in Go. Instead of string a value type, pointer stores address of another variable. Pointer points to address of another variable in Go. To get address of variable, we use & operator. To get value that pointer points to, we use * operator.

main.go
a := 10
b := &a
fmt.Printf("Value of a is %d \n", a)
fmt.Printf("Address of a is %v\n", &a)
fmt.Printf("Value at pointer location is %v\n", *b)

Pointer Type

Like we can declare variables to hold different types of values in Go, we can also declare pointer that holds address of different Go types. Variable intP is pointer to int type while floatP is pointer to float64 type. Similar to value types, we can not assign pointer of type X to pointer of type Y.

main.go
var intP *int
var floatP *float64
fmt.Println(intP, floatP)

Pointer to structure

It is common to use Pointers with struct in Go. Since it is common use case, for de-referencing (getting value out of pointer) Go does not require us to use asterisk (*) symbol. Instead of (*myLocation).street we can use myLocation.street

main.go
type location struct {
	street  string
	city    string
	pincode int
}

myLocation := &location{
	street:  "Xyz",
	city:    "Pune",
	pincode: 444101,
}

fmt.Printf("I live on %s street, %s city with %d code\n",
	myLocation.street, myLocation.city, myLocation.pincode)

Sharing Data

Main use of pointers is to share data between function calls. Pointers when used efficiently help us increase system performance by sharing data instead of making a fresh copy every time between function calls. updateLocation function accepts pointer to location type and it can update myLocation variable value using pointer.

main.go
type location struct {
	street  string
	city    string
	pincode int
}
func main() {
	myLocation := &location{
		street:  "Xyz",
		city:    "Pune",
		pincode: 444101,
	}

	fmt.Printf("I live on %s street, %s city with %d code\n",
		myLocation.street, myLocation.city, myLocation.pincode)

	// sharing data
	updateLocation(myLocation)

	fmt.Printf("I live on %s street, %s city with %d code\n",
		myLocation.street, myLocation.city, myLocation.pincode)
}

func updateLocation(loc *location) {
	loc.city = "Mumbai"
}

Blog Resources

Last updated