Pointers in Go: Difference between revisions
Line 37: | Line 37: | ||
fmt.Printf("%v\n", aPtr) // same thing | fmt.Printf("%v\n", aPtr) // same thing | ||
</syntaxhighlight> | </syntaxhighlight> | ||
For more details on the pointer, including the type of the data it points to, use: | |||
<syntaxhighlight lang='go'> | |||
fmt.Printf("%#v\n", aPtr) | |||
</syntaxhighlight> | |||
This will print: | |||
<font size=-2> | |||
(*int)(0xc000012080) | |||
</font> | |||
=Pointer Variable Name= | =Pointer Variable Name= |
Revision as of 23:52, 28 September 2023
External
Internal
Overview
A pointer is a data type that represents a virtual address in memory, usually the address of a location in memory that is referred by a variable.
A pointer can be declared as such:
var aPtr *int // a pointer to an int
It can also be implicitly declared using the short variable declaration and the the referencing operator inside functions:
a := 10
aPtr := &a
aPtr
is a pointer that contains the memory address that points to the memory location associated with the variable a
. Changing the memory value using a syntax that involves the pointer will surface in the value of the variable:
*aPtr = 20
println(a) // will display 20
The pointer data type comes with two operators: &
(the referencing operator), and *
(the dereferencing operator).
Displaying Pointers
To display the value at memory address stored in the pointer, must dereference:
fmt.Printf("%d\n", *aPtr)
To display the memory address stored in the pointer in a hexadecimal notation use %p
or %v
, they are equivalent for pointers:
fmt.Printf("%p\n", aPtr)
fmt.Printf("%v\n", aPtr) // same thing
For more details on the pointer, including the type of the data it points to, use:
fmt.Printf("%#v\n", aPtr)
This will print:
(*int)(0xc000012080)
Pointer Variable Name
Do we use someNamePtr
or someName
?
Also see:
The Referencing Operator &
The referencing operator (the ampersand operator) returns an address, also known as a "reference", from a variable. &
should be read as "address of ...". It works with variables and also with literals. The syntax &user{name:"Bill"}
where user
is a struct
is legal. The address is represented internally as an instance of type pointer
. The address points to the location in memory where the instance associated with the "referenced" variable is stored.
&<variable-name>
color := "blue"
pointerToColor := &color
println(pointerToColor) // prints "0xc000058720"
The Dereferencing Operator *
The dereferencing operator (star operator) takes a pointer and returns the value in memory the pointer's address points toward. The variable must contain a pointer type instance, otherwise the code will not compile. The value thus exposed can be read or written.
*<pointer-name>
color := "blue"
pointerToColor := &color
println(*pointerToColor) // prints "blue"
*pointerToColor = "red"
println(color) // prints "red"