Convert Interface to Type: Type Assertion
·
285 words
·
2 minutes read
If you’ve ever come across messages like these, you’ll no doubt have used type assertion already. This is a post explain how and why to use it.
|
|
|
|
Functions and packages will at times return interface{}
as a type because the type would be unpredictable or unknown to them. Returning interface allows them to pass data around without know it’s type.
Not knowing the variable’s true type however means that later down the line, many calls on this data won’t work - like the +=
operation in our example below. So we type assert it by placing the type in brackets after the variable name.
|
|
You’ve probably noticed this doesn’t allow for much in the way of error handling. But it’s also possible to use a variant of type assertion which returns if it ran ok (like the snippet of code below).
|
|
There’s also a number of StackOverflow questions that explain this well.