What is the meaning of this type declaration?

前端 未结 1 1189
长情又很酷
长情又很酷 2021-01-16 07:41

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.c

相关标签:
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.

    0 讨论(0)
提交回复
热议问题