1. interface struct 能否相互嵌套
- struct struct //继承(不能多态), 如果内部struct实现了接口, 它也相当于实现了接口
- struct interface //可以内部用interface多态
- interface interface //单纯的导入
- interface struct //不允许
2. struct方法参数定义指针还是值
无论方法参数定义成指针还是值, 都可以调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| package main
import "fmt"
type S struct { age int }
func (s S) Value() { fmt.Println(s.age) }
func (s *S) Point(age int) { s.age = age }
func main() {
s := new(S) s.Point(1) s.Value() fmt.Println(s)
v := S{} v.Point(2) v.Value() fmt.Println(v) }
|
3. interface 能否赋值实现了的 struct
3.1 struct是值的都可以赋值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| package main
import "fmt"
type I interface { Get() } type S struct { }
func (s S) Get() { fmt.Println("get") }
func main() {
var i I
i = S{} i.Get()
i = &S{} i.Get() }
|
3.2 struct是指针的只能指针赋值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| package main
import "fmt"
type I interface { Get() } type S struct { }
func (s *S) Get() { fmt.Println("get") }
func main() {
var i I
i = &S{} i.Get() }
|
4. interface实现多态
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| package main
import "fmt"
type P interface { Say() } type P1 struct{} type P2 struct{}
func (p *P1) Say() { fmt.Println("say p1") } func (p *P2) Say() { fmt.Println("say p2") }
func main() { p1 := &P1{} p2 := &P2{}
var p P p = p1 p.Say() p = p2 p.Say() }
|
5. 组合继承并不会多态
go 语言中,当子类调用父类方法时,“作用域”将进入父类的作用域,看不见子类的方法存在。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| package main
import "fmt"
type A struct { }
func (a *A) ShowA() { fmt.Println("showA") a.ShowB() } func (a *A) ShowB() { fmt.Println("showB") }
type B struct { A }
func (b *B) ShowB() { fmt.Println("b showB") }
func main() { b := B{} b.ShowA() }
|