In the above example, we define an 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. 2.42.1. 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*/ }
2.42.2. 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() }
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!