类型转换和类型断言之间有什么区别?

类型转换和类型断言之间有什么区别?

问题描述:

之间的主要区别是什么?

What is the main differences between :

  1. v = t.(aType)//类型断言
  2. v = aType(t)//类型转换

我应该在哪里使用类型断言或类型转换?

Where should I use type assertion or type conversion ?

类型断言断言 t (接口类型)实际上是 aType t 将是 aType ;即包裹在 t 接口中的那个.例如.如果您知道您的 var reader io.Reader 实际上是一个 * bytes.Buffer ,则可以执行 var br * bytes.Buffer = reader.(* bytes.缓冲区).

A type assertion asserts that t (an interface type) actually is a aType and t will be an aType; namely the one wrapped in the t interface. E.g. if you know that your var reader io.Reader actually is a *bytes.Buffer you can do var br *bytes.Buffer = reader.(*bytes.Buffer).

类型转换将一种(非接口)类型转换为另一种类型,例如像 var id int64 = int64(x)那样的 var x uint8 到int64.

A type conversion converts one (non-interface) type to another, e.g. a var x uint8 to and int64 like var id int64 = int64(x).

经验法则:如果您必须将具体类型包装到接口中并希望返回具体类型,请使用类型断言(或类型切换).如果需要将一种具体类型转换为另一种具体类型,请使用类型转换.

Rule of thumb: If you have to wrap your concrete type into an interface and want your concrete type back, use a type assertion (or type switch). If you need to convert one concrete type to an other, use a type conversion.