What is the difference between type conversion and type assertion?

前端 未结 1 1205
死守一世寂寞
死守一世寂寞 2021-01-31 08:27

What is the main differences between :

  1. v = t.(aType) // type assertion
  2. v = aType(t) // type conversion

Where shou

相关标签:
1条回答
  • 2021-01-31 08:52

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

    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.

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