capypad
0 day streak
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
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main
import "fmt"
 
type Person struct {
Name string
Age int
}
 
func main() {
person := Person{Name: "Max", Age: 25}
fmt.Println(person.Name, "is", person.Age)
 
pointer := &person
fmt.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