douyou1960 2016-08-07 05:40
浏览 18
已采纳

去:嵌入原始类型?

Suppose we have this piece of code:

type User struct {
    int32
    Name string
}

Can this type of embedding be useful?
Does int32 have any methods which other can call on instances of User?
How can I access the value of the int32 that User is embedding?

  • 写回答

1条回答 默认 最新

  • dst2017 2016-08-07 05:51
    关注

    The type int32 is a predeclared type, it has no methods. To verify:

    fmt.Println(reflect.TypeOf(int32(0)).NumMethod()) // Prints 0
    

    You can refer to all embedded fields by using the unqualified type name as the field name (Spec: Struct types), predeclared types are no exception. See this example:

    u := User{3, "Bob"}
    fmt.Printf("%#v
    ", u)
    u.int32 = 4
    fmt.Println(u.int32)
    

    Output (try it on the Go Playground):

    main.User{int32:3, Name:"Bob"}
    4
    

    Primary gain of using embedding is:

    • methods of the embedded type get promoted, so it's easier to implement interfaces (you don't need to provide methods that get promoted)

    • you can "override" methods of the embedded type (on the embedder type): provide your own implementation which will be called when a value of your embedder type is used

    • and fields of the embedded type get promoted, so code is shorter to refer to promoted fields (field name is left out).

    By embedding predeclared types such as int32, you don't get any advantage over using just a regular field (named, not embedded field), as the int32 type doesn't have any methods or fields.

    Going forward, besides not having any advantage, you even have a disadvantage. Since predeclared type names start with lowercased letters, embedding them implicitly makes them unexported, so you can only refer to them in the declaring package of the embedder type. If you make them regular, named fields, you may choose to use an uppercased name to make it exported, or a lowercased name to make it unexported.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败