Golang:Type Assertions

A type assertion is an operation applied to an interface value. Syntactically, it looks like x.(T), where x is an expression of an interface type and T is a type, called the "asserted" type. A type assertion checks that the dynamic type of its operand matches the asserted type.

There are two possibilities. First, if the asserted type T is a concrete type, then the type assertion checks whether x's dynamic type is identical to T. If this check succeeds, the result of the type assertion is x's dynamic value, whose type is of course T. In other words, a type assertion to a concrete type extracts the concrete value from its operand. If the check fails, then the operation panics. For example:

var w io.Writer
w = os.Stdout
f := w.(*of.File)   // success: f == os.Stdout
c := w.(*bytes.Buffer)   // panic: interface holds *os.File, not *bytes.Buffer

Second, if instead the asserted type T is an interface type, then the type assertion checks whether x's dynamic type satisfies T. If this check succeeds, the dynamic value is not extracted; the result is still an interface value with the same type and value components, but the result has the interface type T. In other words, a type assertion to an interface type changes the type of the expression, making a different (and usually larger) set of methods accessible, but it preserves the dynamic type and value components inside the interface value.

/*
如果T是 interface 类型,type assertion 就是检查 x 的动态类型是否满足 T。 如果检测成功,获取到的检测结果仍然是一个接口类型(和 x有相同的 类型和值),但是该检测结果会有 接口类型 T;
换句话说,type assertion 会改变表达式的类型,通常使其有更多的方法集,但是它保存了接口值内部的动态类型和值的部分
*/

After the first type assertion below, both w and rw hold os.Stdout so each has a dynamic type of *os.File, but w, an io.Writer, exposes only the file's Write method, whereas rw exposes its Read method too.

var w io.Writer
w = os.Stdout
rw := w.(io.ReadWriter)   // success: *os.File has both Read and Write.  io.ReadWriter 是一个接口类型,此时会检测 w能否满足 io.ReadWriter 这个接口

w = new(ByteCounter)
rw = w.(io.ReadWriter)  // panic: *os.ByteCounter has no Read method

上述代码中的第一组 w 和 rw,都持有 os.Stdout 类型。

原文地址:https://www.cnblogs.com/neozheng/p/13584101.html