Module lessons (1/5)
Defining and using a struct
A struct groups named fields into a single type. It is Go's way
of building "objects" — more literal and immediate than classes, with
no inheritance and no built-in constructors.
Declaration
type Person struct {
Name string
Age int
}type introduces a new named type. Fields are written one per
line, name type. Consecutive fields of the same type can share the
declaration: X, Y int.
Creation
// with named fields (recommended: robust to reordering)
p := Person{Name: "Ada", Age: 36}
// positional (fragile: depends on declaration order)
q := Person{"Ada", 36}
// zero value: every field at its zero value
var r Person // r = {Name: "", Age: 0}
// pointer: allocate with & or new
ptr := &Person{Name: "Ada"}
ptr2 := new(Person) // *Person to a zero-value structField access
p := Person{Name: "Ada", Age: 36}
fmt.Println(p.Name, p.Age)
p.Age = 37 // mutation (if p is a variable)On a pointer, ptr.Name works directly: Go performs the
implicit dereference. No -> like in C.
Visibility: the uppercase rule
Fields with an uppercase initial are exported (visible from other packages); lowercase = private to the current package.
type User struct {
Name string // exported
salt []byte // private to the package
}The same rule applies to every identifier in Go: types, functions, variables, fields.
Anonymous and nested structs
// anonymous (handy for ad-hoc data)
config := struct {
Host string
Port int
}{Host: "localhost", Port: 8080}
// nested
type Address struct {
Street string
City string
}
type Customer struct {
Name string
Address Address
}Comparability
Two structs are comparable with == if ALL their fields are
comparable (no slices/maps/funcs inside):
a := Person{Name: "Ada", Age: 36}
b := Person{Name: "Ada", Age: 36}
fmt.Println(a == b) // trueThis also lets you use them as map keys.
Try it
Define the Person type with Name string and Age int, then instantiate it as {Name: 'Ada', Age: 36} in main.
Show hint
Syntax: `type Name struct { Field Type; ... }`.
Solution available after 3 attempts
Print the value of the Name field of p (an existing Person).
Show hint
Field access: `p.Field`.
Solution available after 3 attempts
What is the visibility of a 'name string' field (lowercase) from another package?
// in package other
type X struct {
name string
}Recap
type Name struct { ... }: new named type with named fields.- Construction:
T{Field: value, ...}(recommended) or positional. - Zero value: every field at its type's zero.
&T{...}andnew(T)for a pointer; implicit dereference (p.Fieldon*T).- Uppercase = exported; lowercase = private to the package.
- Structs are comparable with
==if all fields are; usable as map keys.