Chapter 11 - Interfaces
Exercise 1: Interfaces
Here we have Cuboid
and Sphere
types, both of which have Volume
and SurfaceArea
methods. We also have a PrintInfo
function that accepts a Cuboid
, and calls Volume
and SurfaceArea
on it so it can print that info.
In the main
function we pass a Cuboid
to PrintInfo
, which compiles fine. But then we try to pass a Sphere
to PrintInfo
as well, which results in a compile error. PrintInfo
is only set up to accept Cuboid
values, even though Sphere
values have identical methods.
Let’s get the PrintInfo
function to accept both Cuboid
and Sphere
values. Define a Solid
interface consisting of Volume
and SurfaceArea
methods. Then modify PrintInfo
to accept a parameter with a Solid
interface type instead of Cuboid
.
Compile Error:
./prog.go:47:11: cannot use s (type Sphere) as type Cuboid in argument to PrintInfo
When you’re ready, have a look at our solution.
Exercise 2: Type Assertions
Here are updated Fan
and CoffeePot
types, both of which satisfy an Appliance
interface. We’ve also added a Use
method that accepts an Appliance
. Currently, Use
only calls the TurnOn
method on the Appliance
…
Update Use
so that it calls Oscillate
on the Appliance
if (and only if) it’s a Fan
. Use
should also call Brew
on the Appliance
if (and only if) it’s a CoffeePot
.
Desired Output:
Windco Breeze
Spinning
Rotating on base
LuxBrew
Powering up
Heating Up
Here’s our solution.