Go, Software Development

Get Your Head Around Golang Interface with Examples

The Golang interface is an interesting construct, and most people from programming languages like Java will find it different. If you are new to Golang, this post helps you get your head around the Golang interface with examples.

Golang Interface in Simpler Terms

The Golang interface is an advanced topic and may require newbies to understand basic programming examples with Golang. For example, we need to know how to declare and initialize variables or structs. Then, learn how to create functions for data types in Golang. In simpler terms, the Golang interface is a construct that defines a set of functions with unique return types and names. Consider the following sample codes that define an interface.

The example Golang Mammal interface represents any mammals like cats, dogs, or people. Notice the function names, parameter lists, and return types. How do we implement an interface in Golang? Any data type in Golang can declare its own set of functions. For instance, we have the following codes that define a function for the type MyType using the built-in string data type.

Implementing a Golang interface means defining the functions for a type with similar function signatures defined in the interface. Therefore, we define all the functions for a type, e.g., struct or string, to implement the Mammal interface. In case we miss one or more functions in the definition,  that type fails to implement the Golang interface. Consider the following example wherein the type Person correctly implements the Mammal Golang interface.

Verify If Interface Implementation Works

How do we verify if our example codes correctly implement the Golang Mammal interface? Suppose we have the following function that accepts a parameter of Mammal type.

Since our example Person type correctly implements the Mammal interface, we can pass an instance of the Person type to the printMammal function.

When we run the main function, we get the following output.

The Complete Golang Interface Example

The complete Golang example codes are as follows.

Have you finally understood Golang interfaces?


Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like