Structs
Declare
type MyStruct struct {
X int
Y int
}Init & Access
func main() {
s := MyStruct{X: 2, Y: 4}
fmt.Println(s.X)
fmt.Println(s.Y)
}Value manipulation
func main() {
s := MyStruct{X: 0, Y: 0}
addOne(&s)
fmt.Println(s.X)
fmt.Println(s.Y)
}
func addOne(s *MyStruct) {
s.X += 1
s.Y += 1
}
// Output: 1, 1Structs are value types, passing them into a method and manipulating is not enough, you must pass the address.
Also note that you do not need to dereference structs. p.X is the same as (*p).X, this is purely because typing the later out would become annoying.
Insta define
func main() {
s := struct {
X int
Y int
}{
X: 1,
Y: 2,
}
fmt.Println(s.X)
fmt.Println(s.Y)
}