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.
package main
import "fmt"
type rectangle struct {
length float64
width float64
}
// YOUR CODE HERE: Convert this function to a method on
// the "rectangle" type named "info".
func rectangleInfo(r rectangle) {
fmt.Println("Length:", r.length)
fmt.Println("Width:", r.width)
}
func main() {
var r rectangle
r.length = 4.2
r.width = 2.3
// YOUR CODE HERE: Update this function call to a
// method call.
rectangleInfo(r)
}
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
// Convert this function to a method on the "rectangle" type.
func makeSquare(r *rectangle) {
if r.length > r.width {
r.length = r.width
} else {
r.width = r.length
}
}
Here’s our solution.