MST

星途 面试题库

面试题:Go语言中组合方法集的基础规则

请简述Go语言中结构体组合时,方法集是如何关联的?结构体指针和结构体值在方法集的使用上有什么区别?
12.0万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试

方法集关联

  1. 匿名字段:在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可以直接调用InnerInnerMethod

  1. 非匿名字段:对于非匿名字段,外层结构体不能直接访问其方法,必须通过字段名来访问。例如:
type Inner struct {
}

func (i Inner) InnerMethod() {
    println("Inner method")
}

type Outer struct {
    inner Inner
}

func main() {
    var o Outer
    o.inner.InnerMethod() 
}

结构体指针和结构体值在方法集使用上的区别

  1. 结构体值的方法集:使用结构体值调用方法时,其方法集只包含接收者为结构体值类型的方法。例如:
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() 这一行会报错,因为结构体值的方法集不包含接收者为指针类型的方法
}
  1. 结构体指针的方法集:使用结构体指针调用方法时,其方法集包含接收者为结构体指针类型和结构体值类型的方法。例如:
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会自动解引用。