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 length
and width
fields. Convert the rectangleInfo
function into an info
method on the rectangle
type.
Output:
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.)
Because makeSquare
needs to modify its receiver, be sure the receiver parameter has a pointer type. And because both the makeSquare
and info
methods are on the same type, it would be a good idea to convert info
to a pointer receiver as well.
Solution
Here’s our solution.