面试题答案
一键面试- 直接创建B实例调用funcA:
- 在Go语言中,当创建B实例并直接调用funcA时,由于B重写了funcA,会调用B中重写的funcA方法。这是因为Go语言的方法调度是基于接收者的实际类型(动态类型)进行的。
- 通过类型断言将B实例转换为A类型后调用funcA:
- 当通过类型断言将B实例转换为A类型后调用funcA,会调用A中的funcA方法。此时,编译器看到的接收者类型是A,所以会调用A的方法,而不是B重写的方法。
以下是验证代码:
package main
import (
"fmt"
)
type A struct{}
func (a A) funcA() {
fmt.Println("This is funcA in A")
}
type B struct {
A
}
func (b B) funcA() {
fmt.Println("This is funcA in B")
}
func main() {
// 直接创建B实例调用funcA
b := B{}
b.funcA()
// 通过类型断言将B实例转换为A类型后调用funcA
var a A = b
a.funcA()
}
运行上述代码,输出如下:
This is funcA in B
This is funcA in A
这就验证了上述不同场景下方法调用的解析情况。