Chapter 10 - Encapsulation and Embedding

Exercise 1: Encapsulation

It shouldn’t be possible, but users of our rectangle type are setting its length and width fields to negative values. We need to encapsulate these fields and add getter and setter methods to control access to them.

Update the rectangle type so that the program below will compile, run, and produce the output shown.

  • Move the rectangle type and all its existing methods to a new shapes package.
  • You’ll need to rename the type and its existing methods so they’re exported from the new package.
  • Leave the struct fields unexported, however, so they can only be accessed through your getter and setter methods.
  • The setter methods should return a single error value. If any value less than 0 is passed, return an error value indicating the value is invalid. Otherwise, return nil.
package main

import (

// check logs an error and exits if the error is not nil.
func check(err error) {
	if err != nil {

func main() {
	var r shapes.Rectangle
	err := r.SetLength(4.2)
	fmt.Println("Length:", r.Length())
	// Set width to an invalid value.
	err = r.SetWidth(-2.3)
	fmt.Println("Width:", r.Width())


Length: 4.2
2019/05/31 18:46:50 invalid width: -2.300000
exit status 1

When you’re ready, have a look at our solution.