Chapter 9 - Defined Types
Exercise 1: Defining Methods
In the last chapter’s exercises, we had you write a
rectangleInfo function that accepted a
rectangle struct value and printed its
width fields. Convert the
rectangleInfo function into an
info method on the
Length: 4.2 Width: 2.3
When you’re ready, have a look at our solution.
Exercise 2: Pointer Receivers for Methods
Now see if you can convert last chapter’s
makeSquare function to a method on the
rectangle type. (That is, calling the
makeSquare method on a
rectangle value should convert that
rectangle to a square.)
makeSquare needs to modify its receiver, be sure the receiver parameter has a pointer type. And because both the
info methods are on the same type, it would be a good idea to convert
info to a pointer receiver as well.
Here’s our solution.