Structs
Defining a Struct
A struct type is declared with 'type Name struct { }', listing each field's name and type. It's Go's way of bundling several related pieces of data into one custom type.
Example: Defining a Struct
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
p := Person{Name: "Asha", Age: 32}
fmt.Println(p.Name, p.Age)
}
Login to try C/C++/Java/PHP code in the editor
Struct Literals
A struct value can be created with a literal listing values for named fields (in any order), or with positional values matching the exact declaration order -- named fields are strongly preferred for readability and safety.
Note: Prefer named fields in struct literals -- they're self-documenting and survive field reordering.
Example: Struct Literals
package main
import "fmt"
type Point struct {
X, Y int
}
func main() {
a := Point{X: 3, Y: 4}
b := Point{5, 6} // positional: X=5, Y=6
fmt.Println(a, b)
}
Login to try C/C++/Java/PHP code in the editor
Modifying Struct Fields
Once you have a struct value, its fields are accessed and modified with dot notation, just like accessing a property on an object in most other languages.
Example: Modifying Struct Fields
package main
import "fmt"
type Counter struct {
Value int
}
func main() {
c := Counter{Value: 0}
c.Value = c.Value + 1
c.Value++
fmt.Println(c.Value)
}
Login to try C/C++/Java/PHP code in the editor
Comparing Structs
Two struct values of the same type can be compared with == as long as every field is itself comparable -- the comparison checks that all fields are equal, not just that they're the same object in memory.
Example: Comparing Structs
package main
import "fmt"
type Point struct {
X, Y int
}
func main() {
a := Point{1, 2}
b := Point{1, 2}
fmt.Println("equal:", a == b)
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting struct field names must be capitalized to be accessible from other packages (exported), not just for style.
- Comparing two structs with == when one of their fields is a non-comparable type like a slice or map, which fails to compile.
- Creating a struct literal with positional values and getting the field order wrong, instead of using named fields for clarity.
- A struct groups related fields together into a single named type.
- Struct literals can use named fields (recommended) or positional values matching declaration order.
- Structs are compared field by field with ==, as long as every field type is itself comparable.
- Structs are the foundation Go uses instead of classes for grouping data.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: