Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
In Go, most variables hold values directly. So if you assign the value "1.23" to a variable, then for all intents and purposes, that's what the variable holds, "1.23". But it's also possible to create a "pointer" to a value. Pointers point to a value in memory. That is, pointers are a value that just gives the address of another value elsewhere in memory.
Pointers point to a value in memory. That is, pointers are a value that just gives the address of another value elsewhere in memory. If you're familiar with object references in C# or Java, those work almost exactly like pointers. And if you already know Pointers from C or C++, Go pointers work almost exactly the same way, except that you can't alter an existing pointer like you can in C or C++.
- To declare a variable that holds a pointer to a type of value, put a star (
*
) before the type. Sovar x float64
declares a variable that holds afloat64
directly, butvar x *float64
declares a variable that holds a POINTER to a afloat64
-
&
: "address of" operator -
*
: gets the value at an address
package main
import "fmt"
func main() {
var aValue float64 = 1.23
var aPointer *float64 = &aValue
fmt.Println("aPointer:", aPointer) // prints something like "aPointer: 0x1040a128"
fmt.Println("*aPointer:", *aPointer) // prints "*aPointer: 1.23"
}
There are a couple circumstances where it's better to use a pointer:
- Function arguments are pass-by-value: the function always receives a COPY of the value
- So if functions alter the value they receive, they'll be altering the copy, not the original
- But if the function receives a pointer, and alters the value that pointer points to, then the function's changes will still be effective outside the function
- For complex values, passing a copy to a function wastes memory.
- Passing a pointer doesn't.
You need to sign up for Treehouse in order to download course files.
Sign up