Writing Our Own Interfaces II

Let’s learn how to implement sort.Interface for 3D shapes.

Implementing sort.Interface for 3D shapes

In this lesson, we will create a utility for sorting various 3D shapes based on their volume, which clearly illustrates the power and versatility of Go interfaces. This time, we will use a single slice for storing all kinds of structures that all satisfy a given interface. The fact that Go considers interfaces as data types allows us to create slices with elements that satisfy a given interface without getting any error messages.

This kind of scenario can be useful in various cases because it illustrates how to store elements with different data types that all satisfy a common interface on the same slice and how to sort them using sort.Interface. Put simply, the presented utility sorts different structures with different numbers and names of fields that all share a common behavior through an interface implementation. The dimensions of the shapes are created using random numbers, which means that each time we execute the utility, we get a different output.

Implementation details

The name of the interface is Shape3D, and it requires the implementation of the Vol() float64 type method. This interface is satisfied by the Cube, Cuboid, and Sphere data types. The sort.Interface interface is implemented for the shapes data type, which is defined as a slice of Shape3D elements.

All floating-point numbers are randomly generated using the rF64(min, max float64) float64 function. As floating-point numbers have a lot of decimal points, printing is implemented using a separate function named PrintShapes() that uses an fmt.Printf("%.2f ", v) statement to specify the number of decimal points that are displayed onscreen—in this case, we print the first two decimal points of each floating-point value.

Get hands-on with 1200+ tech skills courses.