From fbb81e5f2c5542d86ffbb0cb8e05ce2640ed65de Mon Sep 17 00:00:00 2001 From: Jasper Ras Date: Sat, 21 Jun 2025 11:11:59 +0200 Subject: vault backup: 2025-06-21 11:11:59 --- What are Type Assertions in Go and when to use them.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 What are Type Assertions in Go and when to use them.md (limited to 'What are Type Assertions in Go and when to use them.md') 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 -- cgit v1.2.3