本文将介绍
继承
、
组合
这些复用概念在golang中是如何体现的。
继承
组合
1.匿名结构体成员—继承
例子1
A1A
A1A
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.
A1a1APrint()继承
例子2
AerPrint()
AA1
test()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
}
func test(ai Aer) {
ai.Print()
}
func main() {
a1 := &A1{}
test(a1)
}
output:
I am A.
AerPrint()A
2.具名结构体成员–组合
例子1
A1Aa
AA1A
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.
从输出结果可以看到,
例子2
AerPrint()
AA1
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
Aer组合
3.参考