Pointers in Go: Difference between revisions
(Created page with "=External= * https://go.dev/ref/spec#Pointer_types =Internal= * Go Language =Overview= A pointer is a data type that represents a virtual address in m...") |
|||
Line 3: | Line 3: | ||
=Internal= | =Internal= | ||
* [[Go_Language#Pointers|Go Language]] | * [[Go_Language#Pointers|Go Language]] | ||
* [[Variables,_Parameters,_Arguments#Pointer|Pointers]] | |||
=Overview= | =Overview= | ||
A pointer is a data type that represents a virtual address in memory. The pointer data type comes with two operators: <code>&</code> (the [[#The_Referencing_Operator_.26|referencing operator]]), and <code>*</code> (the [[#The_Dereferencing_Operator_.2A|dereferencing operator]]). | A pointer is a data type that represents a virtual address in memory. The pointer data type comes with two operators: <code>&</code> (the [[#The_Referencing_Operator_.26|referencing operator]]), and <code>*</code> (the [[#The_Dereferencing_Operator_.2A|dereferencing operator]]). |
Revision as of 22:58, 28 September 2023
External
Internal
Overview
A pointer is a data type that represents a virtual address in memory. The pointer data type comes with two operators: &
(the referencing operator), and *
(the dereferencing operator).
A pointer can be declared as such:
var ip *int // a pointer to an int
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"