Erstellt von Alex Danyluik
vor etwa 4 Jahre
|
||
Definition: An interface is a method set (i.e. collection of methods) and an interface type is simply that specify this interface. interface := {Method1, Method2, Method3, .., MethodN} A variable of interface type can be of any type T if and only if the interface is the subset of the method set of T. Which is also known as type T implements the interface. method_set_T = {It is the method set of type T} method_set_T is a superset of interface. The value of uninitialized variable of type interface is nil.
InterfaceType = "interface" "{" { ( MethodSpec | InterfaceTypeName ) ";" } "}" . MethodSpec = MethodName Signature . MethodName = identifier . InterfaceTypeName = TypeName .
We can write an interface in go by specifying methods explicitly through method specifications (as shown above) //A simple file interface interface { Read([]byte) (int, error) Write([]byte) (int, error) Close() error } Every methodName should be unique (among the interface) and not blank (_)
More than one type can implement the same interface. For example if s1 and s2 are two types than they can both implement the same interface (for e.g. file interface). func (p T) Read(p []byte) (n int, err error) func (p T) Write(p []byte) (n int, err error) func (p T) Close() error where T is either s1 or s2. (regardless of what other methods s1 and s2 contains) A type implements any interface comprising any subset of its methods and may therefore implement several distinct interfaces. For instance, all types implement the empty interface: interface{} Interface type: type Locker interface { Lock() Unlock() } If S1 and S2 also implement func (p T) Lock() { … } func (p T) Unlock() { … } They implement the Locker interface as well as the File interface.
An interface T may use a (possibly qualified) interface type name E in place of a method specification. This is called embedding interface E in T. The method set of T is the union of the method sets of T’s explicitly declared methods and of T’s embedded interfaces. A union of method sets contains the (exported and non-exported) methods of each method set exactly once, and methods with the same names must have identical signatures. An interface type T may not embed itself or any interface type that embeds T, recursively.
Ref : This notes have been written under the guidance of the go language specification book. All the examples are also taken from it. (https://golang.org/ref/spec#Interface_types)
Möchten Sie kostenlos Ihre eigenen Notizen mit GoConqr erstellen? Mehr erfahren.