Structs
Production applications regularly work with data that doesn't fit neatly into a single primitive type. A User has a name, an email and an age. A Server has an address, a port and a timeout. Go's struct type lets you define your own composite data types for this, grouping related fields together under a single name.
A struct is defined using the type and struct keywords:
type Point struct { X float64 Y float64}Each line inside the braces declares a field: a name followed by a type. Fields can be of any type: primitives, other structs, slices, maps, or pointers. Together, they describe the shape of the data your type holds.
Here is a more complete example:
type Student struct { Name string Age int Grade float64 Active bool}Once defined, Student is a full type in Go: you can declare variables of that type, pass it to functions, store it in slices, and use it anywhere a type is expected.
Zero value struct
The zero value of a struct is a struct where every field is set to its own zero value: 0 for numeric types, false for booleans, "" for strings, and nil for pointers, slices, maps, and interfaces.
A zero value struct can be created with a var declaration:
var s Studentfmt.Println(s.Name) // ""fmt.Println(s.Age) // 0fmt.Println(s.Grade) // 0fmt.Println(s.Active) // falseIt can also be created with a short variable declaration using an empty struct literal:
s := Student{}Both forms produce identical results: a fully initialized struct where every field holds its type's zero value.
Initializing field values
Go provides two syntaxes for initializing a struct with specific values.
Implicit (positional) initialization: you provide the values in the exact order the fields are declared, without field names:
s := Student{"Alice", 20, 9.1, true}This is compact but fragile. If you add or remove a field, every positional callsite stops compiling until you update it. Reordering two fields of the same type is worse: the code still compiles, and each value lands in the other field.
Explicit (named) initialization: you write each field name next to its value:
s := Student{ Name: "Alice", Age: 20, Grade: 9.1, Active: true,}This is the idiomatic style in Go. Fields can appear in any order, and any field you omit is automatically set to its zero value. This form is resilient to changes in the struct definition.
Dot notation
Fields are read and written using dot notation: variable.FieldName.
Reading a field:
s := Student{Name: "Alice", Age: 20, Grade: 9.1, Active: true}fmt.Println(s.Name) // "Alice"fmt.Println(s.Age) // 20fmt.Println(s.Grade) // 9.1fmt.Println(s.Active) // trueWriting a field:
s := Student{Name: "Alice", Age: 20, Grade: 9.1, Active: true}s.Age = 21s.Grade = 9.5fmt.Println(s.Age) // 21fmt.Println(s.Grade) // 9.5Dot notation works the same way however the struct was created, whether with var, a struct literal or any other form.