Interface in Golang


January 19, 2022, Learn eTutorial
1321

In this tutorial, you will learn about interfaces in Golang. Some of the basics of interfaces like what is interface in Golang and how to declare an interface in the Go programming language. We will also consider the difference between an interface and a struct. Further, you will learn how to implement a go program using the interface.

What is an interface in Golang?

An interface is a mechanism in which any unrelated entities interact with each other. It mainly describes the behavior of an entity. An entity is any physical object.
For example, if a thing barks, moves eats, or bites like a dog then that thing can be distinguished as a DOG. The type of DOG is not focused we do focus only on its behavior.
Let us understand the concept with an example 

GO : Interface

Consider a power socket and some electrical devices like a TV, kettle, laptop, a printer that requires a power supply to work with these devices. The socket is unaware of the various electrical devices that are going to plug into the socket to power up. These devices need to be connected to the socket to draw power. So in order to connect to the socket these devices need a common interface. A power drawer interface acts as an interface between the socket and the electrical devices to enable their connection to operate. The power drawer draws power to any connected device. The socket has a plug method that accepts any device that has a draw method. Each electrical device has a power draw method to consume power from the socket.

GO : Interface
  •   A Socket can power up any device.
  •   To power up there should be a draw method i.e. a power drawer.
  •   In this example, the power socket is unaware of all the devices types.
  •   Devices need to draw power from the power socket.
  •   So electrical devices implement a power drawer interface, to implement that they use the draw method.
  •   The socket power up the devices using the draw method.
  •   In brief interfaces couple different types of each other which help in creating more maintainable programs 
  •   You can add more electrical devices without changing the type of socket.

Note: An interface is a protocol of abstract type it does not have implementation it only describes the expected behavior from a type.

Let us consider another example a TV (television) remote which acts as an interface between the user and the TV. The device remote helps the user to interact with the TV.

GO : Interface

Another example is API (application programming interface) which provides an interface between the front end and back end of software. The front end is the one visible to the user and the back end is where processing occurs.

In Golang programming an interface lists the functions that a particular type can perform. Basically in an interface, you can define the things that a particular type can perform. In the case of humans, the activities humans can perform like eating, sleeping, walking, etc. So it can be categorized that whoever performing these tasks can be a human.

Note: Interfaces are not implemented, it just defines the things a particular type can perform and this type is implemented not the defined interface.

An interface defines the set of available operations/methods.

What is a concrete type in Golang?

Concrete type is the opposite type of abstract type. All the types are concrete types except the interface type.

GO : Interface

Note: Concrete types are formed by all non-interface type

What is an interface type?

  •   the interface type is a set of method signatures. 
  •  A method signature is composed of the name of methods and a list of parameters which includes type, number, and order of parameters.
  •  An interface type holds any values that implement methods defined inside the interface type.

How to declare an interface?

Ingo programming language an interface is a type with a set of methods within it. The interface forms collection of methods or method signatures that defines the behavior of similar type entities or objects.
Syntax to define an interface:  


type<interface name=""> keyword interface {
method1
method2
            …….
}

In the above syntax type<interface name> keyword interface, states that the type of particular name is an interface. Then open a curly bracket within which encloses all the method signatures like method1, method2 etc. and syntax ends with a closing bracket.
Let us see an example 


 type shape interface {
   area () float64
}

The syntax defines a type called the shape of interface type and a method area () of type float64 inside the curly braces.

GO : Interface

Note: An interface defines the expected behavior only.

How to implement an interface in Golang?

Let us understand what an interface is and how to implement an interface with a program given below.

In the program, there is a circle and rectangle with similar behavior. And there include two functions to call circle area and rectangle area. Both these functions are defined with different implementations but both have a common area.
So based on the theory you know both circles and rectangles have some shapes and areas.

The interface allows you to look at these types as if they are the same and hides the details underneath and just look at the facts, here the fact is both have areas.
The interface defines some behavior that is similar between objects or similar between types. The below-given types are of the same kind with their related behavior.


type circle struct{
 radius float64
}
type rectangle struct{
 length float64
 breadth float64
}

In the program, we have created a slice for C1 for the circle and R1 for the rectangle. A slice shape with some type for C1 and R1 is declared. Assume the type here is unknown.

shapes :=[]type{C1,R1}

In order to identify the type we need to define the interface as below


type shape interface{
  area() float64
}

Since both function (func)for circle and rectangle have a method called area() they implement the interface shape.

GO : Interface

So from the above discussion, you understood that interface can be used as any concrete type. We got an idea of the type we have to use during slice declaration, you can replace the type mentioned therewith with an interface type that is shaped as below.

shapes :=[]shape{C1,R1}

Both circle and rectangle implement the shape interface you can use the type as shape and can put it together inside the slice defined. Even after the declaration of the interface the functions circle and rectangle cannot be accessed through the interface. In order to access it, we use dot operation. The shape.area () access the fields inside circle and rectangle which in turn is put inside a for loop statement in below program like


for _,shape := range shapes{
 fmt.Println(shape.area())

Now let us look at the whole code given below, which prints circle and rectangle areas.

GO : Control-flow

Program with an interface


package main
import (
     "fmt"
     "math"
)
type shape interface{
  area() float64
}

type circle struct{
 radius float64
}


type rectangle struct{
 length float64
 breadth float64
}

func (r rectangle) area() float64{
return r.length * r.breadth
}

func (c circle) area() float64{
return math.Pi * c.radius *c.radius
}

func main(){
C1 := circle{2}
R1 :=rectangle{5,2}
shapes :=[]shape{C1,R1}

for _,shape := range shapes{
 fmt.Println(shape.area())
}
}

Output:


12.566370614359172
10

Note: An interface can be used with any kind of type, in the above program we used as slice type it can be of variable type, return type, parameter type, etc. All these different types are able to be used under interface type.

What is stringer in Golang?

Stringer is a type implemented in the fmt package. Stringer type describes itself as a string. Stringer interface is used by fmt packages to print values.

Syntax to create a stringer  


type Stringer interface {
    String () string
}

Where

  •   type is a keyword,
  •   Stringer is the interface name
  •   the interface is a keyword
  •   String () is the only method inside a Stringer interface of a type string.

How to Implement a Stringer interface?

Stringer is a tool that automates method creation which satisfies fmt. Stringer interface.

Syntax


func (t T) String() string{

}

Example


package main
func (s SITE) String() string {
 return s.Name
}

In the given program a new type of SITE is declared. The main function consists of an instance “S” of type SITE. When the below-given code runs get output that prints values of struct fields i.e. Name, language, year, tutorial.

Program before using Stringer interface


package main
import (
 "fmt"
)

/*A struct is a type which contains named fields.
Define new type named 'SITE'*/
type SITE struct {
  Name    string
 language    string
 year  int
 tutorial []string
}
func main() {

 /*initialize a struct.
   Create an instance of type 'SITE'*/
 S := SITE{"learn eTutorials","GO", 2022,[]string{"JAVA", "C"}}
 fmt.Println(S)
}

Output:


{learn eTutorials GO 2022 [JAVA C]}

It is possible to change the text as shown in the output below as

Output:


{learn eTutorials GO 2022 [JAVA C]}

The string method of the stringer interface is used to implement this property.


/**SITE  type implements the method "String" of "Stringer" interface.*/
func (s SITE) String() string {
 return s.Name
}

The above-given function implements the string method of the Stringer interface where the type is SITE which returns the name of SITE when you run the code it prints the output Learn tutorials.

The program implements a stringer interface


/*A struct is a type which contains named fields.
Define new type named 'Person'*/
type SITE struct {
  Name    string
 language    string
 year  int
 tutorial []string
}

/**SITE  type implements the method "String" of "Stringer" interface.*/
func (s SITE) String() string {
 return s.Name
}
func main() {

 /*initialize a struct.
   Create an instance of type 'Person'*/
 S := SITE{"learn eTutorials","GO", 2022,[]string{"JAVA", "C"}}
 fmt.Println(S)
}

Output:


Learn eTutorials

This stringer interface enables override the behavior. You can print the output as language defined in struct type by changing the return type into return s.language  which prints the language “GO”.


**SITE type implements the method "String" of "Stringer" interface.*/
func (s SITE) String() string {
 return s.language 
}

Output:


GO