This is a creation in Article, where the information may have evolved or changed.
Keyword interface
- If a struct-bound method contains all the methods of an interface, that interface is considered implemented
- When an object is assigned to an interface, a copy occurs, and the storage of the interface points to the copied pointer, the copy cannot be modified, and the pointer cannot be obtained.
type CallBack interface{ getName() string}type User struct{ name string}func (user User) getName()string{ return user.name}user:=User{}f.println(user.getName())
- The above declares a callback, the struct user binds a getname method, the same as the interface name declared by the callback interface, and implements all methods of the callback interface (he now only declares an interface method). So the struct user implements the callback interface
- Interfaces can be nested with interfaces, a bit like structure nesting
type CallBack interface{ getName() string BaseCall}type BaseCall interface{ doSomething()}func (user User) doSomething(){ f.println("something to do")}func (user User) getName()string{ return user.name}user:=User{}user.doSomething()f.println(user.getName())
- Gets the object of the implemented struct based on the interface, and takes some action
//强制转换,判断User结构体是否实现了CallBack接口func hasInterface(callback CallBack){ if u,ok:=callback.(User);ok{ f.Println("name is:",u.name) return } f.Println("not has interface")}
- In the Golang, so the structure of the implementation of an empty interface, so, the above can be modified to a better scalability of the judgment, which, in accordance with which, T automatically strong to the type
func hasInterface(intf interface{}){ switch t:=intf.(type){ case User: f.println("struct is:",t.name) default: f.println("unknow") }}
- The interface can be strong, but only up and down, that is, the external interface can be strongly into the nested interface, but the inside of the interface is not strong to the external interface, a bit like inheriting subclass strong to the parent class, but the parent class can not be strong rotor class
CallBack: = user{info:info{name: "Key le"}}var base basecallbase=basecall (callBack) base.dosomething ()