Go by Example - Structs
Go by Example - Structs
com/structs
Go by Example: Structs
Go’s structs are typed collections of fields. They’re
useful for grouping data together to form records.
package main
import "fmt"
This person struct type has name and age fields. type person struct {
name string
age int
}
newPerson constructs a new person struct with the func newPerson(name string) *person {
given name.
func main() {
You can name the fields when initializing a struct. fmt.Println(person{name: "Alice", age: 30})
An & prefix yields a pointer to the struct. fmt.Println(&person{name: "Ann", age: 40})
You can also use dots with struct pointers - the sp := &s
pointers are automatically dereferenced. fmt.Println(sp.age)
$ go run structs.go
{Bob 20}
{Alice 30}
{Fred 0}
&{Ann 40}
&{Jon 42}
Sean
50
51
{Rex true}
1 of 2 11/26/24, 23:34
Go by Example: Structs https://gobyexample.com/structs
2 of 2 11/26/24, 23:34