English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In Go language, an interface is a collection of method signatures, which is also a type, meaning you can create variables of interface type. In Go language, you can create multiple interfaces in your program using the given syntax:
type interface_name interface{ //method signature }
Note:In Go language, it is not allowed to create the same named method in two or more interfaces. If you try to do so, your program will crash. Let's discuss multiple interfaces with an example.
//concept of multiple interfaces package main import "fmt" // interface 1 type AuthorDetails interface { details() } // interface 2 type AuthorArticles interface { articles() } // struct type author struct { a_name string branch string college string year int salary int particles int tarticles int } //Implement Interface Method1 func (a author) details() { fmt.Printf("Author: %s", a.a_name) fmt.Printf("\nDepartment: %s Through Date: %d", a.branch, a.year) fmt.Printf("\nSchool Name: %s", a.college) fmt.Printf("\nSalary: %d", a.salary) fmt.Printf("\nNumber of Published Articles: %d", a.particles) } // Implement Interface Method 2 func (a author) articles() { pendingarticles := a.tarticles - a.particles fmt.Printf("\nPending Articles: %d", pendingarticles) } // Main value func main() { //Structural Assignment values := author{ a_name: "Mickey", branch: "Computer science", college: "XYZ", year: 2012, salary: 50000, particles: 209, tarticles: 309, } // access using the interface1method var i1 AuthorDetails = values i1.details() //access using the interface2method var i2 AuthorArticles = values i2.articles() }
Output:
Author: Mickey Department: Computer science Through Date: 2012 School Name: XYZ Salary: 50000 Number of Published Articles: 209 Pending Articles: 100
Usage Explanation:As shown in the example above, we have two interfaces with methods, namely details() and Articles(). Here, the details() method provides the basic details of the author, while the articles() method provides the pending articles of the author.
There is also a structure named Author(Author) that contains a set of variables, whose values are used in the interface. In the main method, we assign the values of existing variables in the Author structure so that they will be used in the interface and create interface type variables to accessAuthorDetailsandAuthorArticlesThe methods of the interface.