go / beginner
Snippet
Structs: Creating Custom Data Types
Structs are composite data types that group together variables of different types under one name. They are the foundation for creating custom objects in Go. You can access fields directly with the dot notation, and passing pointers to structs allows functions to modify the original data.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package mainimport "fmt"type Person struct {Name stringAge int}func main() {person := Person{Name: "Max", Age: 25}fmt.Println(person.Name, "is", person.Age)pointer := &personfmt.Println("Via pointer:", pointer.Name)}
Breakdown
1
type Person struct {
Declares a new custom type called Person
2
Name string
Field named Name of type string
3
Age int
Field named Age of type int
4
person := Person{Name: "Max", Age: 25}
Creates instance with named fields for clarity
5
pointer := &person
Creates pointer to the person struct
6
pointer.Name
Go automatically dereferences pointer for field access