Go Language Interface
The Go language provides another type of data interface, which defines all the common methods, and any other type implements this interface as long as it implements these methods.
Instance
1 /*Defining Interfaces*/2Type Interface_nameInterface {3 method_name1 [Return_type]4 method_name2 [Return_type]5 Method_name3 [Return_type]6 ...7 method_namen [Return_type]8 }9 Ten /*Define structure Body*/ OneType Struct_namestruct { A /*variables*/ - } - the /*Implementing 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*/ A}Instance
1 Package Main2 3 Import (4 "FMT"5 )6 7Type PhoneInterface {8 Call ()9 }Ten OneType Nokiaphonestruct { A } - - func (Nokiaphone nokiaphone) call () { theFmt. Println ("I am Nokia, I can call you!") - } - -Type IPhonestruct { + } - + func (iphone iphone) call () { AFmt. Println ("I am iPhone, I can call you!") at } - - Func Main () { - varPhone Phone - -Phone =New(Nokiaphone) in Phone.call () - toPhone =New(IPhone) + Phone.call () - the}
In the example above, we define an interface phone with a method call () inside the interface. Then we define a phone type variable in the main function and assign it to Nokiaphone and iphone, respectively. The call () method is then called and the output is as follows:
I am Nokia, I can call you! I am iPhone, I cancall you!
Go Language Interface