donglian3055 2015-08-14 09:48
浏览 50
已采纳

Go中的结构初始化和方法声明

I am new of Go, and pretty curious of structs. Let's define a struct T

type T struct {
    size int
}
  1. I have seen different types of struct initialization. What are the differences?

    new(T)     // 1
    T{size:1}  // 2
    &T{size:1} // 3
    
  2. And the two types of method declarations:

    func (r *T) area() int // 1
    func (r T) area() int  // 2
    

    What should be the right way?

  • 写回答

2条回答 默认 最新

  • douqiaosu0280 2015-08-14 09:58
    关注
    1. allocation

    new and &T{size:1} returns *T

    T{size:1} return T

    The built-in function new takes a type T, allocates storage for a variable of that type at run time, and returns a value of type *T pointing to it. The variable is initialized as described in the section on initial values.

    2.

    The method set of any other named type T consists of all methods with receiver type T. The method set of the corresponding pointer type *T is the set of all methods with receiver *T or T (that is, it also contains the method set of T).

    var pt *T

    var t T

    func (r *T) area() int

    you can use pt.area() or t.area()

    func (r T) area() int

    you can use t.area(), can't use pt.area()

    usually we use func(r *T) area() int

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)