Multiple Interfaces in Golang
Last Updated :
11 Apr, 2023
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
// 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.
Here's an example code demonstrating multiple interfaces in Go:
Go
package main
import "fmt"
type Reader interface {
Read() string
}
type Writer interface {
Write(string)
}
type ReadWriter interface {
Reader
Writer
}
type Document struct {
content string
}
func (d Document) Read() string {
return d.content
}
func (d *Document) Write(content string) {
d.content = content
}
func main() {
doc := &Document{content: "Initial content"}
// using the Reader interface to read the document content
var r Reader = doc
fmt.Println("Content before writing:", r.Read())
// using the Writer interface to write new content to the document
var w Writer = doc
w.Write("New content")
// using the ReadWriter interface to read the updated document content
var rw ReadWriter = doc
fmt.Println("Content after writing:", rw.Read())
}
Output:
Content before writing: Initial content
Content after writing: New content
In this example, we define three interfaces: Reader, Writer, and ReadWriter. The ReadWriter interface embeds both the Reader and Writer interfaces.
We then define a Document struct that has a content string field. We implement the Read method on the Document type to return the value of the content field, and the Write method to update the content field with a new value.
In the main function, we create a new Document instance and assign it to the doc variable. We then use the Reader interface to read the initial content of the document, followed by the Writer interface to write new content to the document. Finally, we use the ReadWriter interface to read the updated content of the document.
Similar Reads
Interfaces in Golang
In Go, an interface is a type that lists methods without providing their code. You canât create an instance of an interface directly, but you can make a variable of the interface type to store any value that has the needed methods.Exampletype Shape interface { Area() float64 Perimeter() float64}In t
3 min read
Type Switches in GoLang
A switch is a multi-way branch statement used in place of multiple if-else statements but can also be used to find out the dynamic type of an interface variable. A type switch is a construct that performs multiple type assertions to determine the type of variable (rather than values) and runs the fi
3 min read
Embedding 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. As we know that the Go language does not support inheritance, but the Go interface fully supports embedding. In embedding, an interface can embed other inter
6 min read
Inheritance in GoLang
Inheritance means inheriting the properties of the superclass into the base class and is one of the most important concepts in Object-Oriented Programming. Since Golang does not support classes, so inheritance takes place through struct embedding. We cannot directly extend structs but rather use a c
3 min read
Templates in GoLang
Template in Golang is a robust feature to create dynamic content or show customized output to the user. Golang has two packages with templates: text/template html/template There are mainly 3 parts of a template which are as follows: 1. Actions They are data evaluations, control structures like loops
4 min read
Golang | Polymorphism Using Interfaces
The word polymorphism means having many forms. Or in other words, we can define polymorphism as the ability of a message to be displayed in more than one form. Or in technical term polymorphism means same method name (but different signatures) being uses for different types. For example, a woman at
4 min read
Parsing Time in Golang
Parsing time is to convert our time to Golang time object so that we can extract information such as date, month, etc from it easily. We can parse any time by using time.Parse function which takes our time string and format in which our string is written as input and if there is no error in our form
2 min read
Multiple Goroutines
Prerequisite: Multiple Goroutines A Goroutine is a function or method which executes independently and simultaneously in connection with any other Goroutines present in your program. Or in other words, every concurrently executing activity in Go language is known as a Goroutines. In Go language, you
2 min read
Nested Structure in Golang
A structure or struct in Golang is a user-defined type, which allows us to create a group of elements of different types into a single unit. Any real-world entity which has some set of properties or fields can be represented as a struct. Go language allows nested structure. A structure which is the
3 min read
Slices in Golang
Slices in Go are a flexible and efficient way to represent arrays, and they are often used in place of arrays because of their dynamic size and added features. A slice is a reference to a portion of an array. It's a data structure that describes a portion of an array by specifying the starting index
14 min read