# 26. Pointers

### Pointers&#x20;

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.

{% code title="main.go" %}

```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)
```

{% endcode %}

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

{% code title="main.go" %}

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

{% endcode %}

### 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`

{% code title="main.go" %}

```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)
```

{% endcode %}

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

{% code title="main.go" %}

```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"
}
```

{% endcode %}

### Blog Resources

{% embed url="<https://www.ardanlabs.com/blog/2013/07/understanding-pointers-and-memory.html>" %}

{% embed url="<https://www.ardanlabs.com/blog/2014/12/using-pointers-in-go.html>" %}

{% embed url="<https://www.ardanlabs.com/blog/2017/05/language-mechanics-on-stacks-and-pointers.html>" %}
