Type conversions and type assertions for the Go language

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

Type conversions and type assertions are the places in the go language that are relatively round.

The go language requires a type conversion to be displayed between the different types of all uniform expressions.
The C language, as the originator of the go language, can be converted directly into implicit type.
Of course, the literal constants of a const class are much more flexible.

However, there are exceptions to the requirement that the go language must do the display type conversion:

    • When T a normal type variable I is converted to an interface type, it is implicit!
    • When an IX interface variable I is converted to an interface type, it can be implicit when the compilation period is complete!

Examples of conversions between types

Here are some examples from the Go Language specification:

*Point(p)        // same as *(Point(p))(*Point)(p)      // p is converted to *Point<-chan int(c)    // same as <-(chan int(c))(<-chan int)(c)  // c is converted to <-chan intfunc()(x)        // function signature func() x(func())(x)      // x is converted to func()(func() int)(x)  // x is converted to func() intfunc() int(x)    // x is converted to func() int (unambiguous)

Simply put, x the syntax that needs to be converted to T type is T(x) .
If you are unsure of the priority in some places, you can () constrain yourself.

The last conversion is an easily confusing statement, so you need to use parentheses to (func() int)(x) increase precedence.

There is also a confusing place for read-only and write-only channel types <-chan int / chan<- int .

Examples of transitions between interfaces

There are many strange features of the type conversion of interfaces in the go language: Sometimes implicit conversions, and sometimes the need for type assertions.

There is also a syntax for casting between the interfaces of the go language, but because implicit conversions are supported between interfaces, interfaces
The cast syntax is just a device.

For example, there are 2 types of interfaces:

type IA interface {}type IB interface {Foo()}

IAWhat do you want to do IB with the transformation? This operation cannot be determined at compile time, so it is not necessarily a type conversion.
Since 2 are all interface types, it is certainly a type assertion:

var a Avar b = a.(B)

Of course, because of the above a code nil , it will result in an a.(B) error.
But please note: This is just a run-time error, not a compilation error!

IBWhat do you want to do IA with the transformation? This operation can be determined at compile time and therefore must be a type conversion.

var b Bvar a = A(b)

As we said earlier, the interface of the go language is implicitly convertible, so you can also omit the cast statement:

var b Bvar a = b

Examples of conversions between interfaces and types

Although there is occasionally a forced-cast syntax between interfaces similar to ordinary types,
But the interface is intended to be a special type (and the common type difference).

Let's first define 2 IA IB normal types (the same as the underlying type) that match the previous/matching:

type TA inttype TB intfunc (TB) Foo() {}

If it is a TA TB conversion between and, you can refer to the example of conversion between the preceding types.
Here we focus on TA TB IA IB The conversion between/and/.

Normal types to interface type conversions are implicit (can be determined by compile-time, implicit conversion privileges of the interface):

var ta TAvar ia = tavar tb TBvar ib = tb

An interface type is a type assertion (run-time determination) to a normal type:

var ia IAvar ta = ia.(TA)var ib IBvar tb = ib.(TB)

Type assertions are not guaranteed at compile time, and the wrong code can be compiled by:

var ta = ib.(TA)var tb = ia.(TB)

Summarize

Because the Go language type conversion and type assertion design is not perfect, it is difficult to generalize easily.

Here is the pseudo-code I've compiled to determine whether a type conversion or a type assertion:

func x 转换为 y    if x 是接口吗 ? {        if 可以编译期转换吗 ? {            这是类型转换 (接口之间可以隐式转换)            // 这里也可以用类型断言, 如果编译期不优化的效率可能低一些        } else {            这是类型断言 (运行时也可能会失败)        }    } else {        if 可以编译期转换 ? {            这是类型转换 (显示转换, 必须成功, 但可能会丢失数据)        } else {            禁止!        }    }}

We can see that when the interface can be converted between types, it is also possible to assert the type.

The transition between the go language interfaces is one of the most confusing features. Expect Go2.0 to improve.

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.