This is a creation in Article, where the information may have evolved or changed.
Interface interface
- An interface is a collection of one or more method signatures
- As long as a type has all the method signatures for that interface, that interface is implemented, without showing which interface the declaration implements, which is called Structural Typing
- Interface as long as method declaration, no implementation, no data field
- Interfaces can be embedded anonymously in other interfaces, or embedded in a structure
- When an object is assigned to an interface, a copy occurs, and the interface stores a pointer to the replica that cannot modify the state of the replica or retrieve the pointer
- The interface is equal to nil only if the interface stores both the type and the object are nil
- Interface calls do not automatically convert receiver
- Interface also supports anonymous field methods
- Interfaces can also be implemented to resemble the polymorphism in OOP
- An empty interface can be used as a container for any type of data
123456789101112131415161718192021222324252627282930313233343536373839404142 |
typeUsbInterface{Name ()stringConnector}typeConnectorInterface{Connect ()}typePhoneconnectorstruct{Namestring} func (PC Phoneconnector) Name() string {returnPc.name} func (PC Phoneconnector) Connect() {FMT. Println ("Connect:", Pc.name)} func main () {A: = phoneconnector{"Phoneconnector"}a.connect () Disconnect (a)//Strong turnA: = phoneconnector{"Phoneconnector"}varP Connectorp = Connector (a) p.connect ()} func Disconnect(USB usb) {ifPc,ok: = USB. (Phoneconnector); OK {fmt. Println (Pc.name)return}fmt. Println ("Unknown Device")} |