Go语言结构体和结构体指针在定义函数时的区别?

定义一个结构体如下:

type VideoItem struct {
    GroupId  int64
    ItemId   int64
    AggrType int32 // Item 还是Group
}

那么如下两个函数有什么区别?

func (item *VideoItem) GetAggrType() int32 {
    return item.AggrType
}
func (item VideoItem) GetAggrType() int32 {
    return item.AggrType
}
阅读 8.1k
2 个回答

这两个都应该称作方法。
很简单,你是用指针作为接收者,那么变量(或者可以称作对象)本身是按引用传递的,在方法内可以修改对象的数据。
使用值接收者,以为这是按值传递的,那么对象在方法内是处于只读状态的。

type VideoItem struct {
    GroupId  int64
    ItemId   int64
    AggrType int32 // Item 还是Group
}

func (item *VideoItem) TestPointer() {
    fmt.Printf("TestPointer %p %v\n", item, item)
}

func (item VideoItem) TestValue()  {
   fmt.Printf("TestPointer %p %v\n", &item, &item)
}
func main(){
    v := VideoItem{}
    fmt.Printf("TestPointer %p %v\n", &v, &v)
    
    v.TestValue()
    v.TestPointer()
    
    //TestPointer 0xc42000a260 &{0 0 0}
    //TestPointer 0xc42000a280 &{0 0 0}
    //TestPointer 0xc42000a260 &{0 0 0}
}

不是指针类型时调用方法会复制receiver,每调用一次TestValue,item就会被复制一次.实际相当于TestValue(v),TestPointer(&v).

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题