go / beginner
Snippet
Structs: Building Custom Data Types
Structs are composite data types that group together zero or more values with different types into a single entity. You define a struct with the type keyword, followed by a name and the struct body containing field declarations. Structs can be initialized using field names (named fields) or positional values, and fields can be accessed and modified using the dot notation.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package mainimport "fmt"type Person struct {Name stringAge int}func main() {person1 := Person{Name: "Alice", Age: 30}person2 := Person{"Bob", 25}var person3 Personfmt.Println(person1.Name)fmt.Println(person2.Age)person3.Name = "Carol"person3.Age = 28fmt.Printf("%+v\n", person3)}
Breakdown
1
type Person struct { ... }
Defines a new struct type called Person
2
person1 := Person{Name: "Alice", Age: 30}
Creates instance with named field initialization
3
person2 := Person{"Bob", 25}
Creates instance with positional values (order matters)
4
var person3 Person
Declares person3 with zero values ("", 0)
5
person3.Name = "Carol"
Access and modify fields using dot notation