Package the main
The import "FMT"
Var CTX TestInt
//TestInt is an interface
Type TestInt interface {
Func1 ()
Func2 ()
Func3 - a non-class function ()
}
Func (* emptyCtx) func1 () {
FMT. Println (" func1 ")
}
Func (* emptyCtx) func2 () {
FMT. Println (" func2 ")
}
Func (* emptyCtx) func3 - a non-class function () {
FMT. Println (" func3 - a non-class function ")
}
Type emptyCtx int
Var (
Background=new (emptyCtx)
)
//Background is a function
Func Background () TestInt {
Return background
}
//Struct1 is a struct
Type Struct1 struct {
TestInt
Str1 string
}
//Struct2 is a struct
Type Struct2 struct {
Struct1
Str2 string
}
Func newStruct1 (parent TestInt) Struct1 {
Return Struct1 {
TestInt: parent,
Str1: "test1",
}
}
//NewStruct2 is a function
Func NewStruct2 (parent TestInt) TestInt {
Return & amp; Struct2 {
: Struct1 newStruct1 (parent),
Str2: "test2",
}
}
Func main () {
CTX:=Background ()
CTX=NewStruct2 (CTX)
CTX. Func1 ()
CTX. Func2 ()
CTX. Func3 - a non-class function ()
}
CodePudding user response:
Feel nothing to illustrate, with easy to understand:Is the interface, B has A, that natural B has A interface
Is just like A is the wiring board, B is house, house has A patch panel. A, B that why B can't use A patch panel?
Interface is a standard
A consistent with the interface specification, then A is the interface of A type
B in line with the interface specification, that B is a type of the interface
TestInt equivalent to formulate A patch panel interface specification (what rule can provide A wiring board, what to provide, such as regulation interface has three slot)
EmptyCtx is according to TestInt standard led to A wiring board, there are three slots
Type Struct1 struct {
TestInt//the wall has a TestInt interface specification (has installed slot)
Str1 string
}
Type Struct2 struct {
Struct1//it has interface with conforming to the guidelines of TestInt wall
Str2 string
}
CTX:=Background ()//produce A wiring board
CTX=NewStruct2 (CTX)//install the wiring board installed in the house of A slot in the
CTX. Func1 ()//house can use strips A slot 1
CTX. Func2 ()//house can use strips A slot 2
CTX. Func3 - A non-class function ()//house can use strips A slot 3
No inheritance in go, only combination
Inheritance is is a relationship, that is, inheritance and parent the same type, the parent class or interface subclass has
Combination is from a relationship, that is, combination with members of the type, some members of the interface combination with