mirror of
https://github.com/alrayyes/wiki.git
synced 2024-11-29 14:36:22 +00:00
70 lines
930 B
Markdown
70 lines
930 B
Markdown
---
|
|
id: 463ce364-f426-4089-a0ca-ffe45f0461f2
|
|
title: Golang Structs
|
|
---
|
|
|
|
# Basics
|
|
|
|
Golang structs are what you expect
|
|
|
|
``` go
|
|
package main
|
|
|
|
import "fmt"
|
|
|
|
type Vertex struct {
|
|
X int
|
|
Y int
|
|
}
|
|
|
|
func main() {
|
|
fmt.Println(Vertex{1, 2})
|
|
}
|
|
```
|
|
|
|
# Struct fields
|
|
|
|
Struct fields are accessed using a dot
|
|
|
|
``` go
|
|
package main
|
|
|
|
import "fmt"
|
|
|
|
type Coorindate struct {
|
|
X int
|
|
Y int
|
|
}
|
|
|
|
func main() {
|
|
coordinate := Coorindate{1, 67}
|
|
coordinate.X = 26
|
|
fmt.Println(coordinate.X)
|
|
}
|
|
```
|
|
|
|
# Struct literals
|
|
|
|
You can also newly allocate a struct by listing the values of its
|
|
fields. This is known as a "struct literal" (duh)
|
|
|
|
``` go
|
|
package main
|
|
|
|
import "fmt"
|
|
|
|
type Vertex struct {
|
|
X, Y int
|
|
}
|
|
|
|
var (
|
|
v1 = Vertex{1, 2} // has type Vertex
|
|
v2 = Vertex{X: 1} // Y:0 is implicit
|
|
v3 = Vertex{} // X:0 and Y:0
|
|
p = &Vertex{1, 2} // has type *Vertex
|
|
)
|
|
|
|
func main() {
|
|
fmt.Println(v1, p, v2, v3)
|
|
}
|
|
```
|