Drills — write struct functions
Structs have to be used, not just read about. Five drills, easy to harder, all on one small record type — a Rectangle. Define it once, then write each function, call it from main, and compare with the solution. (We have structs, functions, if and basic types — no loops or slices yet, and none of these need them.)
type Rectangle struct {
Width int
Height int
}
1 (easy) — newRectangle. Build a Rectangle from two numbers and return it. Use a named literal so it's obvious which field is which.
newRectangle(3, 4) → {3 4}
func newRectangle(w, h int) Rectangle {
return Rectangle{Width: w, Height: h}
}
2 (easy) — area. Read the fields with the dot and multiply.
area(newRectangle(3, 4)) → 12
func area(r Rectangle) int {
return r.Width * r.Height
}
3 (medium) — isSquare. Compare two fields of the same struct, return a bool.
isSquare(newRectangle(5, 5)) → true isSquare(newRectangle(3, 4)) → false
func isSquare(r Rectangle) bool {
return r.Width == r.Height
}
4 (medium) — scaled, and the copy trap. Return a rectangle with both sides multiplied by factor. Now the important part — check what happens to the original:
func scaled(r Rectangle, factor int) Rectangle {
r.Width *= factor
r.Height *= factor
return r
}
r := newRectangle(3, 4)
big := scaled(r, 2)
fmt.Println(big, r) // {6 8} {3 4}
Look: r is still {3 4} even though scaled assigned to r.Width and r.Height. A struct is passed by copy — the function edited its own duplicate, and the only way the change reaches you is the return. This is the struct version of the copy trap from lesson 3, and it bites everyone once.
5 (harder) — larger. Take two rectangles, return the one with the bigger area (reuse area).
larger(newRectangle(2, 2), newRectangle(3, 4)) → {3 4}
func larger(a, b Rectangle) Rectangle {
if area(a) >= area(b) {
return a
}
return b
}
Tip. Notice how
largercallsareainstead of repeatingWidth * Height— small functions built on smaller ones is the whole game. Print each result and match it against the examples. These are exactly the kind of pure functions we'll lock down withgo testin lesson 13.