Chapter 9 - Defined Types

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

package main

import "fmt"

type rectangle struct {
	length float64
	width  float64
}

// makeSquare needs to modify the "rectangle" value,
// so the receiver needs to be a pointer.
func (r *rectangle) makeSquare() {
	// Again, no need to write (*r).length; Go gets
	// the value at the pointer automatically.
	if r.length > r.width {
		r.length = r.width
	} else {
		r.width = r.length
	}
}

// Don't forget to change the "info" method to take a
// pointer receiver as well!
func (r *rectangle) info() {
	fmt.Println("Length:", r.length)
	fmt.Println("Width:", r.width)
}

func main() {
	var longRectangle rectangle
	longRectangle.length = 4.2
	longRectangle.width = 2.3
	// Because the method receiver parameter has a
	// pointer type, Go automatically converts the
	// value to a pointer.
	longRectangle.info()
	longRectangle.makeSquare()
	longRectangle.info()
	var wideRectangle rectangle
	wideRectangle.length = 10
	wideRectangle.width = 20
	// Because the method receiver parameter has a
	// pointer type, Go automatically converts the
	// value to a pointer.
	wideRectangle.info()
	wideRectangle.makeSquare()
	wideRectangle.info()
}

Output:

Length: 4.2
Width: 2.3