Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Medium

Polymorphism Using Interfaces in Go

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Go is a general-purpose programming language with a focus on systems programming. It is strongly typed, garbage-collected, and supports concurrent programming explicitly. Packages are the building blocks of programs, and their attributes allow for efficient dependency management. Google engineers created Go to construct stable and efficient software. 

This article will give you enough information on polymorphism using interfaces in Go to let you go to higher levels of expertise. Before reading this article, you should have a basic understanding of computer programming terms. It will be pretty simple for you to grasp the principles if you have a decent command of C. If that is not the case, you can return here after reading our Introduction to C article.

Polymorphism in GoLang


Polymorphism refers to a message's ability to appear in multiple forms. A lady, for example, can have various characteristics at the same time. As a mother, wife, sister, employee, and so forth. As a result, the same person behaves differently in different settings. Polymorphism is the term for this. Polymorphism is one of the most significant elements of Object-Oriented Programming, and it can be performed at runtime or during compilation. 


Golang is an Object-Oriented programming language that solely enables polymorphism through interfaces. The interfaces are implicitly implemented in Go, as we already know. When we construct an interface, and other kinds desire to implement it, those types utilize the interface's methods to implement it without knowing the type. A variable of an interface type can hold any value that implements the interface in an interface. In the Go programming language, this characteristic aids interface polymorphism. Let us understand with the help of an example:

Example

Interface is implemented by a variable of type interface that can hold any value. This property of interfaces is used to achieve polymorphism in Go.

Let's understand polymorphism in Go with the help of a program that calculates the total pages read by the student.


// Go program to illustrate the concept
// of polymorphism using interfaces
package main
import "fmt"
// Interface
type student interface {
pagecount() int
name() string
}

// Structure 1
type book1 struct {
totalpage_1 int
name_1 string
}

// Methods of employee interface are
// implemented by the team1 structure
func (b1 book1) pagecount() int {
return b1.totalpage_1
}


func (b1 book1) name() string {
return b1.name_1
}


// Structure 2
type book2 struct {
totalpage_2 int
name_2 string
}


// Methods of employee interface are
// implemented by the team2 structure
func (b2 book2) pagecount() int {
return b2.totalpage_2
}


func (b2 book2) name() string {
return b2.name_2
}


func finalpagecount(i []student) {

totalpagecount := 0
for _, ele := range i {


fmt.Printf("\nBook Name = %s\n ", ele.name())
fmt.Printf("Total number of pages %d\n ", ele.pagecount())
totalpagecount += ele.pagecount()
}
fmt.Printf("\nTotal pages read by "+"the student = %d", totalpagecount)


}


// Main function
func main() {


res1 := book1{totalpage_1: 180,
name_1: "The Great Gatsby"}


res2 := book2{totalpage_2: 256,
name_2: "Miss Pettigrew Lives for a Day"}


final := []student{res1, res2}
finalpagecount(final)
}

Output

Book Name = The Great Gatsby
 Total number of pages 180
Book Name = Miss Pettigrew Lives for a Day
 Total number of pages 256
Total pages read by the student = 436

Check out this article - Compile Time Polymorphism

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Frequently Asked Questions

Is it possible to compare structs in Golang?

If two structures are of the same type and have the same values for all fields, Golang allows you to compare them.

In Golang, how do you use methods?

Go language support methods. The only distinction between Go methods and Go functions is that the method has a receiver parameter. The method can access the receiver's properties using the receiver argument. The receiver can be either struct or non-struct in this case.

What Is Compile-time Polymorphism?

Method overloading is used to provide compile-time polymorphism. Method overloading refers to the ability to have multiple methods with the same name. Compile-Time Polymorphism is the name given to this technique since it occurs during the compilation phase.

Is polymorphism the same as overloading?

Polymorphism refers to an item having multiple forms that perform different operations depending on the requirements. Method overloading occurs when you write two or more methods in the same class with the same name but different parameters.

In Golang, what is function?

A function is a collection of statements in a program that are used to complete a particular activity. A function, at its most basic level, takes an input and returns an output. You can use functions to combine multiple code blocks into a single component.

Conclusion

This article extensively discussed polymorphism using interfaces in Go.

We hope you have learned something new from this blog. And if you're interested in learning more, see our posts on Structs in GoClasses and ObjectsExploring the dynamics of GolangWhat is GolangGo Race Condition in Golang. Please vote for our blog to help other ninjas succeed.

Visit our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more.!

Happy Reading!

 

Topics covered
1.
Introduction
2.
Polymorphism in GoLang
2.1.
Example
2.2.
Output
3.
Frequently Asked Questions
3.1.
Is it possible to compare structs in Golang?
3.2.
In Golang, how do you use methods?
3.3.
What Is Compile-time Polymorphism?
3.4.
Is polymorphism the same as overloading?
3.5.
In Golang, what is function?
4.
Conclusion