This article will introduce Inherit
、 Combine
These reuse concepts are in golang How is it embodied in .
stay golang in , Through anonymous struct members , Access to methods defined in anonymous structs , It's the so-called real Inherit
.
Through named structural members , You can also access the methods defined in the struct , That's what's called Combine
.
1. Anonymous struct members --- Inherit
Example 1
Structure A1
Contains anonymous structs A
.
Definition A1
The variable of a1, adopt a1 visit A
Methods .
package main
import (
"fmt"
)
type A struct {
}
func (t *A) Print(){
fmt.Println("I am A.")
}
type A1 struct {
A
}
func main() {
a1 := A1{}
a1.Print()
}
output:
I am A.
As you can see from the output ,A1
Structural variables a1
Access to A
Defined in a structure Print()
Method . That is to say A1 Inherit
了 A.
Example 2
Defining interfaces Aer
, It contains methods Print()
.
Then define A
、A1
.
A1 Contains anonymous structs A.
Define test functions test()
, The parameter is Aer
Interface type .
package main
import (
"fmt"
)
type Aer interface {
Print()
}
type A struct {
}
func (t *A) Print(){
fmt.Println("I am A.")
}
type A1 struct {
A
}
func test(ai Aer) {
ai.Print()
}
func main() {
a1 := &A1{}
test(a1)
}
output:
I am A.
You can see from the output that ,A1 Realized Aer
Interface Print()
Method .
And this is actually " Inherit " since A
.
2. Members of a named structure -- Combine
Example 1
Structure A1
Contains the structure A
Variable of type a
.
Defining structure A
The variable of a, Then use a Defining structure A1
Type variable
a1.
Finally through a1 visit a, Re pass a visit A
Methods .
package main
import (
"fmt"
)
type A struct {
}
func (t *A) Print(){
fmt.Println("I am A.")
}
type A1 struct {
a A
}
func main() {
a := A{}
a1 := A1{a}
a1.a.Print()
}
output:
I am A.
As you can see from the output ,
Example 2
Defining interfaces Aer
, It contains methods Print()
.
Then define A
、A1
.
A1 Contains the structure A Type variable a As a member variable .
Last , test A1 Whether the interface is implemented Aer
.
package main
import (
"fmt"
)
type Aer interface {
Print()
}
type A struct {
}
func (t *A) Print(){
fmt.Println("I am A.")
}
type A1 struct {
a A
}
func main() {
a := A{}
a1 := A1{a}
var i interface {} = a1
ai, ok := i.(Aer)
if ok {
fmt.Println("a1 implement Aer")
ai.Print()
} else {
fmt.Println("a1 not implement Aer")
}
}
output:
a1 not implement Aer
You can see through the results , Structure A1 There is no interface implemented Aer
.
in other words , adopt Combine
The way , No, " Inherit " Related methods .