What is the main differences between :
v = t.(aType) // type assertion
v = aType(t) // type conversion
Where shou
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.