What is the meaning of this type declaration?

狂风中的少年 提交于 2019-12-01 10:26:28

问题


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:


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.



来源:https://stackoverflow.com/questions/49402138/what-is-the-meaning-of-this-type-declaration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!