summaryrefslogtreecommitdiff
path: root/What are Type Assertions in Go and when to use them.md
diff options
context:
space:
mode:
authorJasper Ras <jras@hostnet.nl>2025-06-21 11:11:59 +0200
committerJasper Ras <jras@hostnet.nl>2025-06-21 11:11:59 +0200
commitfbb81e5f2c5542d86ffbb0cb8e05ce2640ed65de (patch)
tree6c5951af8530f003b8e3311c62d75802052ba363 /What are Type Assertions in Go and when to use them.md
parent0d389e1d6c1aed4a92f82d9711f4564a12390fcd (diff)
vault backup: 2025-06-21 11:11:59
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