Vai lingua dell'interfaccia
lingua Go fornisce un altro tipo di dati che è l'interfaccia, che insieme con la definizione di tutti i metodi hanno in comune, e qualsiasi altro tipo implementa questi metodi è quello di implementare questa interfaccia.
Esempi
/* 定义接口 */ type interface_name interface { method_name1 [return_type] method_name2 [return_type] method_name3 [return_type] it. method_namen [return_type] } /* 定义结构体 */ type struct_name struct { /* variables */ } /* 实现接口方法 */ func (struct_name_variable struct_name) method_name1() [return_type] { /* 方法实现 */ } it. func (struct_name_variable struct_name) method_namen() [return_type] { /* 方法实现*/ }
Esempi
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() }
Nell'esempio precedente, definiamo un telefono interfaccia, l'interfaccia che ha una chiamata di metodo (). Poi definiamo una variabile nella principale tipo di funzione del telefono all'interno, e ai quali hanno assegnato NokiaPhone e iPhone. Quindi chiamare metodo call (), i risultati di output sono i seguenti:
I am Nokia, I can call you! I am iPhone, I can call you!