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 newshapes
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 than0
is passed, return an error value indicating the value is invalid. Otherwise, returnnil
.
Output:
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.