doujie1908 2018-03-21 09:09
浏览 29
已采纳

此类型声明的含义是什么?

I am actually learning golang (from .NET) and there is one thing I don't understand about this language. Sometimes I find this kind of declaration:

https://github.com/golang/crypto/blob/master/ed25519/ed25519.go

// PublicKey is the type of Ed25519 public keys.
type PublicKey []byte

What does it mean exactly? Is it a creating a struct which inherit from []byte?

Is it just an alias?

I thought golang forbid inheritance.

  • 写回答

1条回答 默认 最新

  • dongxi7704 2018-03-21 09:15
    关注

    It's a type declaration, more specifically a type definition. It creates a new type, having []byte as its underlying type:

    A type definition creates a new, distinct type with the same underlying type and operations as the given type, and binds an identifier to it.

    New types are created because they can simplify using them multiple times, their identifier (their name) may be expressive in other contexts, and–most importantly–so that you can define (attach) methods to it (you can't attach methods to built-in types, nor to anonymous types or types defined in other packages).

    This last part (attaching methods) is important, because even though instead of attaching methods you could just as easily create and use functions that accept the "original" type as parameter, only types with methods can implement interfaces that list ("prescribe") those methods, and as mentioned earlier, you can't attach methods to certain types unless you create a new type derived from them.

    As an example, the type []int will never implement the sort.Interface required to be sortable (by the sort package), so a new type sort.IntSlice is created (which is type IntSlice []int) to which the required methods are attached, so you can pass a value of type sort.IntSlice to the sort.Sort() function but not a value of type []int. Since sort.IntSlice has []int as its underlying type, if you have a value of []int, you can simply convert it to sort.IntSlice if you want to sort it, like in this example (try it on the Go Playground):

    is := []int{1,3,2}
    sort.Sort(sort.IntSlice(is))
    fmt.Println(is) // Prints: [1 2 3]
    

    When you create a new type, there is no "inheritance" involved. The new type will have 0 methods. If you want "inheritance-like" functionality, you should check out embedding (in relation with struct types), in which case the embedder type will also "have" the methods of the embedded type.

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

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)