Go-Programming-I-Pointers-in-Golang
Bond。James Bond。
A pointer is a special type that is used to reference a value. Understanding it better can help you write advanced code in Go.
Variables
Computer memory can be thought of as a sequence of boxes, placed one after another in a line. Each box is labeled with a unique number, which increments sequentially. The unique location number is called a memory address.
A variable is just a convenient, alphanumeric nickname for a piece of memory location assigned by the compiler. When you declare variables, you are given a memory location to use from the free memory available.
Pointers
A pointer value is the address of a variable. A pointer is thus the location at which a value is stored. With a pointer, we can read or update the value of a variable indirectly, without using or even knowing the variable’s name, if indeed it has a name.
In the following example,
- The statement &x yields a pointer to an integer variable.
- y := &x We say y points to x, or y contains the address of x.
- The expression
*y
yields the value of that integer variable, which is 9 here.
Why is pointer useful?
“Pointers are used for efficiency because everything in Go is passed by value so they let us pass an address where data is held instead of passing the data’s value, to avoid unintentionally changing data, and so we can access an actual value in another function and not just a copy of it when we want to mutate it.”
Pointers Example
A copy of the value is sent to a function as an argument in pass-by-value. Any changes in the function will only impact the function’s variable; it will not update the original value outside of the function scope.
1 | package main |
Result:
1 | User[Name: John, Age: 30] |
Pass by pointer
In Go, everything is passed-by-value. We use pointers when we want to pass by reference and set the original value.
1 | package main |
Result:
1 | User[Name: John, Age: 30] |