Go language interface


Release date:2023-09-20 Update date:2023-10-13 Editor:admin View counts:203

Label:

Go language interface

Go language provides another data type, the interface, which definesall common methods together, and any other type implements this interface as long as they implement these methods.

Example

/* Define interfaces */
type interface_name interface {
   method_name1 [return_type]
   method_name2 [return_type]
   method_name3 [return_type]
   ...
   method_namen [return_type]
}
/* Define Structure */
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 Phone , there is a method inthe interface call() . And then we’re here. main function definesa Phone type variable and assign it a value of NokiaPhone and IPhone . And then call call() method, and the output is as follows:

I am Nokia, I can call you!
I am iPhone, I can call you!

Powered by TorCMS (https://github.com/bukun/TorCMS).