面试题答案
一键面试方法集关联
- 匿名字段:在Go语言结构体组合中,当一个结构体包含匿名字段时,外层结构体可以直接访问匿名字段的方法,就好像这些方法是外层结构体自己的一样。例如:
type Inner struct {
}
func (i Inner) InnerMethod() {
println("Inner method")
}
type Outer struct {
Inner
}
func main() {
var o Outer
o.InnerMethod()
}
这里Outer
结构体包含Inner
匿名字段,Outer
实例o
可以直接调用Inner
的InnerMethod
。
- 非匿名字段:对于非匿名字段,外层结构体不能直接访问其方法,必须通过字段名来访问。例如:
type Inner struct {
}
func (i Inner) InnerMethod() {
println("Inner method")
}
type Outer struct {
inner Inner
}
func main() {
var o Outer
o.inner.InnerMethod()
}
结构体指针和结构体值在方法集使用上的区别
- 结构体值的方法集:使用结构体值调用方法时,其方法集只包含接收者为结构体值类型的方法。例如:
type MyStruct struct {
value int
}
func (s MyStruct) ValueMethod() {
println("Value method")
}
func (s *MyStruct) PointerMethod() {
println("Pointer method")
}
func main() {
var s MyStruct
s.ValueMethod()
// s.PointerMethod() 这一行会报错,因为结构体值的方法集不包含接收者为指针类型的方法
}
- 结构体指针的方法集:使用结构体指针调用方法时,其方法集包含接收者为结构体指针类型和结构体值类型的方法。例如:
type MyStruct struct {
value int
}
func (s MyStruct) ValueMethod() {
println("Value method")
}
func (s *MyStruct) PointerMethod() {
println("Pointer method")
}
func main() {
var sPtr *MyStruct = &MyStruct{}
sPtr.ValueMethod()
sPtr.PointerMethod()
}
Go语言在调用指针方法集的方法时,会自动进行值和指针的转换。如果使用结构体值调用指针方法,Go会自动取其地址;如果使用结构体指针调用值方法,Go会自动解引用。