Interfaces
This Go program demonstrates the use of interfaces and polymorphism. It defines an interface named geometry
with methods area
and perim
. Two struct types, rect
and circle
, implement this interface by providing their own versions of the area
and perim
methods. The measure
function takes a geometry
interface as a parameter and calls its methods. Finally, in the main
function, instances of rect
and circle
are created, and the measure
function is called on each of them.
Let's go through each part of the code with inline comments and additional explanations:
Output
Explanation:
The
geometry
interface is defined with two methods,area
andperim
.Two struct types,
rect
andcircle
, implement thegeometry
interface by providing their own versions of thearea
andperim
methods.The
measure
function takes a parameter of typegeometry
and prints information about it, including calling thearea
andperim
methods.In the
main
function:An instance of the
rect
struct (r
) and an instance of thecircle
struct (c
) are created.The
measure
function is called for both therect
andcircle
instances, demonstrating polymorphism. The function can work with any type that implements thegeometry
interface, allowing for flexibility and code reusability.
Last updated