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.

Solution

package main

import "fmt"

type rectangle struct {
	length float64
	width  float64
}

// Convert the regular parameter to a receiver parameter
// on the rectangle type.
func (r rectangle) info() {
	fmt.Println("Length:", r.length)
	fmt.Println("Width:", r.width)
}

func main() {
	var r rectangle
	r.length = 4.2
	r.width = 2.3
	// Change the function call to a method call.
	r.info()
}

Output:

Length: 4.2
Width: 2.3