Types you define · 3 MIN READ
A struct is data, and its fields have names
Declare a struct type and build values of it without positional guessing.
A struct groups fields under a type name. Point{X: 1, Y: 2} names its fields; Point{1, 2} relies on declaration order. Reordering same-typed fields can silently change an unkeyed literal's meaning. Adding a field usually makes an existing unkeyed literal fail to compile. Keyed literals make intent clearer, and vet checks unkeyed literals for structs from other packages.
A struct's zero value is a struct, not nil. Each field begins at its own zero value. Fields beginning with an uppercase letter are exported; visibility is decided per field.
SEE THE IDEA
Field names make construction readable
- 01
Type
gotype Point struct { X, Y int }A fixed set of fields
- 02
Keyed literal
goPoint{X: 3}Omitted fields receive zero values
- 03
Copy
gonext := pointCopies the struct value
A struct value carries its fields together; assigning it copies that value.
In practice
Prefer keyed literals when the field meanings are not obvious. An omitted field is deliberately zero, which is helpful for configuration structs. A struct copy is shallow: slice, map and pointer fields still refer to the same backing data even though the outer struct is a new value.
Watch out
A copied struct containing a mutex must not be used as an independent lock after the original lock has been used.
Work through the exercise
package main
// Declare a Rect type with Width and Height fields of type int,
// then finish Area so it returns their product.
func Area(r Rect) int {
return 0
}
func main() {
println(Area(Rect{Width: 3, Height: 4}))
}Trace each value and write down your reasoning. Copy the source into GopherForge or your local Go environment to compile and check it. This web page does not execute your code or send it to a compiler service.
Progress stays in this browser. No account needed.