Learn about type aliases for Go 1.9

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Catalogue [−]

    1. Type aliases
    2. The difference between type naming and type declaration
    3. Type loop
    4. Exportable
    5. Method set
    6. Byte and Rune types
    7. Resources

As you know, the type aliases is eventually added to go 1.9, the Go 1.9 Beta2 has been released today, the official version is expected to be released in early August, it is time to delve into its new features, this article is about one of its important new features: type aliases.

Of course, if you want to try these new features, you will need to install the version of Go 1.9, which is currently in version Beta2 and can be downloaded on the official website.

Type aliases are the main solution to what the problem is, why do you need this feature? Russ Cox's thesis codebase refactoring (with help from Go) introduces its background. Type aliases are mainly used in:

    1. When refactoring project code on a large scale, especially when moving a type from one package to another, some code uses the type in the new package, and some code uses the types in the old package, such ascontext
    2. Allows a large package to be decomposed into a few small packets inside, but the type in the packet needs to be concentrated and burst into the large package of the upper layer.

Type aliases

The syntax for type aliases is as follows:

1
type identifier = Type

It is similar to the type definition, except that an equal sign is added to and from the type definition, but it is identifier Type very different from the = definitions of the types, which are later specifically compared.

The following example string defines an alias for a string type, S you can declare a variable, a constant as a S type, assign a string to it, and it is almost identical to the string type.

12345678910
 Package mainimport"FMT"typestringfunc Main () {var "Hello World"fmt. Println (s)}

Of course, you can define type aliases for any type, there are no restrictions in the language specification, you can define aliases for arrays, structs, pointers, functions, interfaces, Slice, maps, channel, and even you can define aliases for types defined by type definition. What's more, you can define aliases for aliases.

For example, an alias is defined for the function type func() F :

12345678910111213
 Package mainimport"FMT"typefunc()func Main () {var func () {FMT. Println ("Hello type aliases")}foo ()}

Again, as in the following code, an interface{} alias is defined G :

12345678910
 Package mainimport"FMT"typeinterface{}func main () {var  "Hello World"fmt. Println (g)}

Type aliases can also define aliases for types in other packages, as long as this type is in other packages exported :

12345678910111213
 Package mainimport ("FMT""Time")type MyTime = time. Timefunc main () {var t MyTime = time. Now () Fmt. Println (t)}

The difference between type naming and type declaration

Remember the following sentence:

The type alias is exactly the same as the original type, but it's just another name.

This sentence hides a lot of wisdom, you can slowly realize.

Exactly the same (identical types) means that the two types of data can be assigned to each other, and the type definition requires a type conversion (Conversion) when assigning values to the original type T(x) .

In this example, the v integer type can be assigned directly d , because the type of D is the D alias of the Integer. And var i I = v this sentence will go wrong, because the I and integer is two types.

So the biggest difference between a type alias and a type definition is that the type alias is the same as the original type, and the type definition and the original type are two different types.

12345678910
 Package maintypeinttypeintfunc Main () {V: =   var d = vvar i i = v}

For example, the type definition type Tnamed Tunderlying , the series type and the combination type are different:

    • TnamedAndTunderlying
    • *TnamedAnd*Tunderlying
    • chan TnamedAndchan Tunderlying
    • func(Tnamed)Andfunc(Tunderlying)
    • interface{ M() Tnamed }Andinterface{ M() Tunderlying }

However, for aliases type T1 = T2 , the following types and combination types are the same:

    • T1AndT2
    • *T1And*T2
    • chan T1Andchan T2
    • func(T1)Andfunc(T2)
    • interface{ M() T1 }Andinterface{ M() T2 }

Another important difference is that the set of methods for a type-defined type has no relation to the set of methods of the original type, and the type alias and the method set of the original type are the same, as described below.

Since the type alias is the same as the original type, in ' Switch-type, you cannot have the original type and the type alias as two branches, because this is a duplicate case:

123456789101112131415161718
 Package mainimport"FMT"typeintfunc Main () {var  Interfacevar d = + v = dswitch I: = V. (type) {case  int: FMT. Println ("It is a int:", I)//Case D://FMT. Println ("It is D type:", i)}}

Type loop

The type alias does not allow a loop definition alias when it is defined, as shown here:

12
type T1 = T2type T2 = T1

The above example is too obvious, the following example is more subtle, but also the loop definition type alias, of course, these compile the code when the compiler will check for you, if there is a circular definition of the situation will be wrong.

12345
type struct {Next *t2} type T2 = T1

Exportable

If the defined type alias is exported (capitalized), then it can be used in other packages, and whether it is OK with the original type exported . In other words, you can unexported define a exported type alias for a type, as in the following example:

12345
type struct string} type T2 = T1

Method set

Since type aliases and primitive types are the same, their set of methods is the same.

The following examples T1 and T3 both have say and greeting methods.

1234567891011121314151617
type struct  {}type T3 = T1func (T1 T1) say () {}func (T3 *t3) greeting () {}func main () {var T1 T1//var t2 T2var t3 t3t1.say () t1.greeting () T3.say () t3.greeting ()}

If the type alias and the original type define the same method, the code is compiled with an error, because there is a duplicate method definition.

Another interesting phenomenon is embedded type that, for example, the following T3 is an T1 alias. When we define structs S , we use anonymous embedding types, so what happens when we call them s.say ? Actually you will compile the error because s.say`不知道该调用 s.t1.say 还是 S.t3.say ', so this time you need to make a definite call.

12345678910111213
type struct {}type T3 = T1func (t T1) say () {}typestruct {t1t3}func main () {var s Ss.say ()}

Further thinking, is it possible for us to add new methods to the types in other libraries, such as adding a tick to the standard library time.Time :

123456789
type Ntime = time. Timefunc (t ntime) Dida () {fmt. Println ("tick Tick")}func main () {t: = time. Now () T.dida ()}

The answer is: NO, the compile time will be error: cannot define new methods on non-local type time.Time .

Byte and Rune types

In Go 1.9, the attributes of the type alias are used internally. For example, the built-in byte type is actually uint8 the type alias, and rune actually is int32 the type alias.

12345678
//Byte is a alias for uint8 and are equivalent to uint8 in all ways. Itis//used, by convention, to distinguish byte values from 8-bit unsigned//integer values. type byte uint8 //Rune is a alias for int32 and are equivalent to int32 in all ways. Itis//used, by convention, to distinguish character values from integer values. type Rune Int32

Resources

    1. https://github.com/golang/proposal/blob/master/design/18130-type-alias.md
    2. https://github.com/ golang/go/issues/18130
    3. https://talks.golang.org/2016/refactor.article
    4. https://github.com/ golang/go/issues/16339
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.