This is a creation in Article, where the information may have evolved or changed.
Prior to the advent of the Go language, the interface was primarily a contractual existence between different components.
1, intrusive interface (almost all of the object-oriented language interface definitions before the go language):
The implementation class needs a clear explanation that it implements an interface (directly specifying an interface). Such as:
Interface IFoo {
void Bar ();
}
Class Foo implements IFoo {//Java grammar
// ...
}
Class Foo:public IFoo {//C + + grammar
// ...
}
2, non-intrusive interface:
Interface definition, there is no need to specify and a specific tired relationship, while defining the class, also do not need to know and that interface is connected.
Advantages:
(1) Go language standard library, no longer need to draw the class Library inheritance tree diagram, you just need to know what this class implementation of the methods, each method is what meaning is enough;
(2) When the implementation of the class, only need to care about what methods they should provide, no longer tangled interface needs to be more thin to be reasonable, the interface is defined by the user on demand, without prior planning;
(3) It is not necessary to introduce a package in order to implement an interface, which can reduce coupling.
Note: in the Go language, a class that instantiates an interface must define a function declared in all interfaces, otherwise it will fail when instantiated, as the following example mentions :
type tmpstruct struct {
structname string
structage, structheight int
}
func (f_struct *tmpstruct) tmpFunc1 () {
FMT. Println ("show info in func1, name is : ", f_struct.structname)
}
func &NBSP; (f_struct< Span style= "Color:rgb (192,192,192)" >&NBSP; *tmpstruct ) &NBSP; tmpFunc2 () &NBSP; {
FMT. Println ("show info in Func2, Age is : ", f_struct.structage)
}
func &NBSP; (f_struct< Span style= "Color:rgb (192,192,192)" >&NBSP; *tmpstruct ) &NBSP; tmpFunc3 () &NBSP; {
FMT. Println ("show info in func3, Height is: ", f_struct.structheight)
}
type tmpinterface interface {
tmpFunc1 ()
TmpFunc2 ()
tmpFunc3 ()
}
type tmpinterface_extern interface {
tmpFunc1 ()
TmpFunc4 ()
}
func Main () {
var inter1 tmpinterface = &tmpstruct{"Name_temp" , A.
inter1.tmpfunc1 ()
Inter1.tmpfunc2 ()
inter1.tmpfunc3 ()
The following code fails to compile back because tmpstruct does not implement All the methods in the Tmpinterface_extern interface
/* the compilation error message is as follows:
cannot Use New (tmpstruct) (Type *tmpstruct) as type Tmpinterface_extern inch Assignment:
*tmpstruct does not implement Tmpinterface_extern (missing tmpFunc4 method ) */
/*
var inter_extern tmpinterface_extern = New (tmpstruct)
inter_extern.tmpfunc1 ()
inter_extern.tmpfunc4 ()
*/
}