How to Use Interface in Golang?

Share Your Love

Since Golang is a statically typed language, the interface is a very potent and crucial component of development. In other words, the interfaces bring development in Golang closer to the Object Oriented Languages paradigm. This tutorial will teach us all there is to know about interfaces and demonstrate how to use them in a program.

So let’s get started.

What Do You Mean by an Interface?

To start with, interfaces enable us to accomplish polymorphism. It represents a group of method signatures and enables us to define the behaviour of the object. Just for the sake of it, consider that the interface has specific methods. A type is considered to implement interfaces when it offers the definitions for each of those methods.

An interface, expressed simply, is a means to see a group of linked types or objects. You should be aware that because the interface is abstract, you cannot make an instance of it.

I’m certain that without looking at a program, this doesn’t make much sense. Let’s do that, then.

Taking a Look at a Program

To begin with, we will create a directory named ‘interface’. I will be saving all my projects in go-workspace, so I’ll type:

cd go-workspace 
mkdir interface 
cd interface
code .

The IDE or text editor opens when we type code. I have the VS Code in my instance. We create a Go source file called the main.go after VS Code has been launched.

package main 
import (
"fmt"
)
type trapezium struct {
basex float64
basey float64
height float64
}
type rhombus struct {
diagonalx float64
diagonaly float64
}
func (t trapezium) area() float64 {
return ((t.basex+t.basey)/2)*t.height
}
func (r rhombus) area() float64 {
return ((r.diagonalx*r.diagonaly)/2) 
}
  • The chunk of code that is written above is easy to comprehend. Two structs have been created. These represent the shapes of the rhombus and trapezium.

The three data fields basex, basey, and height in the trapezium struct are all of type float64. The rhombus struct includes two data fields of type float64, diagonal and diagonally.

  • Next, you can see that the behaviour of the trapezium and the rhombus is comparable; they have “area” common them. Even if they each have distinct implementations, you may still refer to the trapezium and rhombus areas.
  • It is clear that the rhombus and trapezium both have shapes and areas. You may see the types (rhombus and trapezium) as if they are the same, courtesy of the interface. The interface doesn’t look at the specifics.

In the meantime, if you have an issue with systems programming or backend development in Golang, you must reach out to the professional developers at Golang.Company. 

#Defining the Interface 
After the import(), we will type: 
type form interface {
area() float64
}

With this, the form interface has been established. According to this interface, any type or struct that has the area() function and returns a float64 is of the form type. In other words, it really implements the interface form. The interface may now be used as a higher-level type of the struct.

#Using the Interface

Now, we will type in the function main.

func main() {
r1 := rhombus {6,4}
t1 := trapezium {8, 6, 4}
forms := []form {r1, t1}
}

We employ the interface in the same manner as any other. You may use the type form to plug the rhombus and trapezium into the slice as they both implement the form interface. The remaining actual characteristics of the rhombus and trapezium are inaccessible through the interface as soon as you utilize it as a type. You can only get access to the area method.

#Incorporating a For Loop

for _, form := range forms {
  fmt.Println (form.area())

When we run the program, we will get to see the following output:

2a27LribOhsjZDOzJPHSzGKMvxWv6xpdHjMLyED391mSlO2vD8TAc39lLV08e9P5REQUrZwolBPh6b5vAD9zJ9Xq1N3g2oz6wEQ5Iev9f1wypKGum6Jjw171zasuZfQTRyTXr 0RTQwD YAdEkdbt KrQI2Le aMQdhWfPU46 5Ck6ffn 1u6rqo

If you implement the interface, you are free to use all of the described behaviour as well as the objects contained within the type interface.

Working on a Function

  • The versatility of interfaces as types is one of their best features. You may use them as parameter types, variable types, or return types; a slice is not a requirement.
  • Whatever you desire, you may include them on a map. You may now utilize all the various kinds under the interface, which adds versatility. Let’s create a function now.
func Result (f form) float64 {
return f.area()
}
  • We are developing a function called Result that takes a f form parameter and returns a float64 value. It will also send back f.area (). As long as it has the area method attached, the shape we are sending here might be either a rhombus or a trapezium.
  • We then go to function main once more. In addition to this, we shall return in the fmt.Println statement. 
fmt.Println (Result (form))

(Point to be Noted: Since this is a different program, we are using a different Go source file named tutorial.go) 

#Methods Accepting a Pointer

Now, we will make the methods accept pointers

func (t *trapezium) area() float64 {
return ((t.basex+t.basey)/2)*t.height
}
func (r *rhombus) area() float64 {
return ((r.diagonalx*r.diagonaly)/2)

As a result, we will also need to make some adjustments to the main function. Since r1 and t1 are values rather than pointers, we are unable to utilize them in the statement forms:= []form { r1, t1}. The following sentence will provide a solution to the issue.

forms := []form {&r1, &t1}

Actually, it is a good habit to constantly pass the pointer when using slices. This is due to the fact that you have access to the pointer if you need it.

You will now see the following output if we execute the program:

dqpPI00Xihr8mTwdjp7fgqEj kmRQxcQrNvvhGT chA8v1Kong5BX16517jFn 7mq67GNpKQhzmfhHaa8S0Zt1hxK6Fj3oR6MJiKc2S 2b047mU6BJvC2QsopuE3

I believe now you have got the hang of the interface concept. You must go through the instruction again if you are still unsure about the concept. You must also look at other examples and try writing code on your own. The more you check out codes and type, the more you will get to understand the significance of interface. 

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 360

Newsletter Updates

Enter your email address below to subscribe to our newsletter