wiki/content/20200828180957-pointers.md

54 lines
960 B
Markdown
Raw Permalink Normal View History

2024-05-06 20:40:05 +00:00
---
2024-10-30 17:34:11 +00:00
date: 2020-08-28
2024-05-06 20:40:05 +00:00
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)
}
```