Multiple Interfaces in Golang
In Go language, the interface is a collection of method signatures and it is also a type means you can create a variable of an interface type. In Go language, you are allowed to create multiple interfaces in your program with the help of the given syntax:
type interface_name interface{ // Method signatures }
Note: In Go language, you are not allowed to create same name methods in two or more interfaces. If you try to do so, then your program will panic. Let us discuss multiple interfaces with the help of an example.
Example:
// Go program to illustrate the // concept of multiple interfaces package main import "fmt" // Interface 1 type AuthorDetails interface { details() } // Interface 2 type AuthorArticles interface { articles() } // Structure type author struct { a_name string branch string college string year int salary int particles int tarticles int } // Implementing method // of the interface 1 func (a author) details() { fmt.Printf( "Author Name: %s" , a.a_name) fmt.Printf( "\nBranch: %s and passing year: %d" , a.branch, a.year) fmt.Printf( "\nCollege Name: %s" , a.college) fmt.Printf( "\nSalary: %d" , a.salary) fmt.Printf( "\nPublished articles: %d" , a.particles) } // Implementing method // of the interface 2 func (a author) articles() { pendingarticles := a.tarticles - a.particles fmt.Printf( "\nPending articles: %d" , pendingarticles) } // Main value func main() { // Assigning values // to the structure values := author{ a_name: "Mickey" , branch: "Computer science" , college: "XYZ" , year: 2012, salary: 50000, particles: 209, tarticles: 309, } // Accessing the method // of the interface 1 var i1 AuthorDetails = values i1.details() // Accessing the method // of the interface 2 var i2 AuthorArticles = values i2.articles() } |
Output:
Author Name: Mickey Branch: Computer science and passing year: 2012 College Name: XYZ Salary: 50000 Published articles: 209 Pending articles: 100
Explanation: As shown in the above example we have two interfaces with methods, i.e, details() and articles(). Here, details() method provides the basic details of the author and articles() method provides the pending articles of the author.
And a structure named as an author which contains some set of variables whose values are used in the interfaces. In the main method, we assign the values of the variables present, in the author structure, so that they will use in the interfaces and create the interface type variables to access the methods of the AuthorDetails and AuthorArticles interfaces.
Please Login to comment...