Go Language Interfaces
The Go language provides another data type called interfaces, which group together all common methods. Any other type that implements these methods is considered to have implemented the interface.
Example
/* Define interface */
type interface_name interface {
method_name1 [return_type]
method_name2 [return_type]
method_name3 [return_type]
...
method_namen [return_type]
}
/* Define struct */
type struct_name struct {
/* variables */
}
/* Implement interface methods */
func (struct_name_variable struct_name) method_name1() [return_type] {
/* method implementation */
}
...
func (struct_name_variable struct_name) method_namen() [return_type] {
/* method implementation */
}
Example
package main
import (
"fmt"
)
type Phone interface {
call()
}
type NokiaPhone struct {
}
func (nokiaPhone NokiaPhone) call() {
fmt.Println("I am Nokia, I can call you!")
}
type IPhone struct {
}
func (iPhone IPhone) call() {
fmt.Println("I am iPhone, I can call you!")
}
func main() {
var phone Phone
phone = new(NokiaPhone)
phone.call()
phone = new(IPhone)
phone.call()
}
In the above example, we define an interface called Phone
with a method call()
. Then, in the main
function, we define a Phone
type variable and assign it to NokiaPhone
and IPhone
. We then call the call()
method, which outputs the following:
I am Nokia, I can call you!
I am iPhone, I can call you!