summaryrefslogtreecommitdiff
path: root/What are Type Assertions in Go and when to use them.md
blob: d23dd669804c4bbaee27eaadc728f6318800ee25 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
[[Golang]]

---
**Form**: `w.(http.Flusher)` where `w` is a variable and `http.Flusher` is an interface. We assert here that `w` implements the `http.Flusher` interface.

A *type assertion* has two return values: first the original value of `w` cast to the type your asserting, and second a boolean that we can check to see if the assertion was successful, generally called `ok`.
i.e.: `flusher, ok := w.(http.Flusher)`. If we don't assign `ok` the program would panic.

### When is this useful?
In the above example where we assert `w.(http.Flusher)` the original specified type of `w` was a `http.ResponseWriter` as per the function argument definition `func x(w http.ResponseWriter).
So we would only be able to call the methods that interface exposes. However, the actual object passed as `w` possibly implements a lot more than just that interface, for example, the `http.Flusher` interface.
By type asserting it and receiving the cast value, we can then call the Flush method on the object.