Search code examples
gotype-conversiontype-assertion

What is the difference between type conversion and type assertion?


What is the main differences between :

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

Where should I use type assertion or type conversion ?


Solution

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