mirror of
https://github.com/alrayyes/wiki.git
synced 2024-11-22 11:36:23 +00:00
53 lines
943 B
Markdown
53 lines
943 B
Markdown
|
---
|
||
|
id: f2e19e3e-e28a-4998-8b0c-38ebfdb559e5
|
||
|
title: Golang Pointers
|
||
|
---
|
||
|
|
||
|
# Basics
|
||
|
|
||
|
Go also supports pointers. Default value is always NULL and you can't do
|
||
|
pointer arithmetic. Other than that, nothing that will blow your mind
|
||
|
here.
|
||
|
|
||
|
``` go
|
||
|
package main
|
||
|
|
||
|
import "fmt"
|
||
|
|
||
|
func main() {
|
||
|
i, j := 42, 2701
|
||
|
|
||
|
p := &i // point to i
|
||
|
fmt.Println(*p) // read i through the pointer
|
||
|
*p = 21 // set i through the pointer
|
||
|
fmt.Println(i) // see the new value of i
|
||
|
|
||
|
p = &j // point to j
|
||
|
*p = *p / 37 // divide j through the pointer
|
||
|
fmt.Println(j) // see the new value of j
|
||
|
}
|
||
|
```
|
||
|
|
||
|
# Pointers to [Golang Structs](20200828181259-structs)
|
||
|
|
||
|
To facilitate lazy people like me Go allows you to lose the \`\*\` when
|
||
|
using a pointer to a struct
|
||
|
|
||
|
``` go
|
||
|
package main
|
||
|
|
||
|
import "fmt"
|
||
|
|
||
|
type Vertex struct {
|
||
|
X int
|
||
|
Y int
|
||
|
}
|
||
|
|
||
|
func main() {
|
||
|
v := Vertex{1, 2}
|
||
|
p := &v
|
||
|
p.X = 123
|
||
|
fmt.Println(v)
|
||
|
}
|
||
|
```
|