Go:嵌入一个原始类型? [英] Go: Embedding a primitive type?

查看:118
本文介绍了Go:嵌入一个原始类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有这段代码:

 类型用户结构{
int32
名称字符串
}

这种嵌入方式是否有用?

int32 有任何其他方法可以调用 User

实例的方法如何访问 用户的嵌套值 int32

解决方案

类型 int32 预先声明的类型,它没有方法。要验证:

$ pre $ f pre $ f pre

您可以使用非限定类型名称作为字段名称来引用所有嵌入字段( Spec:Struct types ),预先声明的类型也不例外。看到这个例子:

$ pre $ u $ User = v \ n,u)
u.int32 = 4
fmt.Println(u.int32)

输出(在 Go Playground 上试用):

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

使用嵌入的主要收益是:


  • 嵌入式类型的方法得到提升,所以它更容易实现接口(你不需要提供被提升的方法)

  • 你可以覆盖嵌入式类型的方法(在嵌入式类型上):提供您自己的实现,当您使用嵌入类型的值时,将调用它。


  • 和字段的嵌入式类型得到提升,因此代码更短以引用提升的字段(字段名称被省略)。


    嵌入预先声明的类型,如 int32 ,你不会像使用 int32 那样仅仅使用常规字段(,而不是嵌入字段) >类型没有任何方法或字段。



    展望未来,除了没有任何优势,您甚至还有一个缺点。由于预先声明的类型名称以小写字母开头,隐式嵌入它们使得它们未导出,所以您只能在嵌入类型的声明包中引用它们。如果您定期输入名称​​ ,您可以选择使用大写的名称来导出它,或使用小写的名称来取消导出。


    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?

    解决方案

    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\n", 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.

    这篇关于Go:嵌入一个原始类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆