summaryrefslogtreecommitdiff
path: root/What are Type Assertions in Go and when to use them.md
diff options
context:
space:
mode:
Diffstat (limited to 'What are Type Assertions in Go and when to use them.md')
-rw-r--r--What are Type Assertions in Go and when to use them.md12
1 files changed, 12 insertions, 0 deletions
diff --git a/What are Type Assertions in Go and when to use them.md b/What are Type Assertions in Go and when to use them.md
new file mode 100644
index 0000000..d23dd66
--- /dev/null
+++ b/What are Type Assertions in Go and when to use them.md
@@ -0,0 +1,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. \ No newline at end of file