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 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看