'Explain Type Assertions in Go
I'm reading about type assertions x.(T) in The Go Programming Language and don't understand them.
I understand that there are different scenarios:
- T is a concrete type or an interface
- One (asserted value?) or two (ok) values can be returned
This is what I don't understand:
- Why would I use them?
- What exactly do they return?
I have also googled on the topic and still don't understand.
Solution 1:[1]
Common usecase: check if returned error is of a type T.
https://golang.org/ref/spec#Type_assertions
For a single return value assertion: when it fails the program panics.
For a two return values assertion: when it fails second argument is set to false and the program doesn't panic.
Solution 2:[2]
A type assertion is the x.(T) notation where x is of interface type and T is a type. Additionally, the actual value stored in x is of type T, and T must satisfy the interface type of x.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kopiczko |
| Solution 2 | Remario |
