Type Assertions
Start with Type Assertions
A type assertion checks whether an interface value holds a particular concrete type or satisfies another interface.
What you’ll learn
- Explain the main purpose of type assertions.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
The safe form number, ok := value.(int) returns a value and a boolean. When the assertion fails, ok is false and number has the zero value of int.
The one-result form number := value.(int) panics if the assertion fails. Use the two-result form when encountering user input, decoded values or other uncertain dynamic types.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func main() {
var data any = "hello"
text, ok := data.(string)
fmt.Println("String:", text, ok)
number, valid := data.(int)
fmt.Println("Integer:", number, valid)
}
Output
String: hello true
Integer: 0 falseTrace what the program does
data holds a string dynamically, so the string assertion succeeds with true. The int assertion fails safely and returns integer zero plus false.
Avoid common mistakes
- Asserting an incorrect type without comma-ok panics.
- A type assertion works on interface expressions, not arbitrary concrete variables.
Try it yourself
Put an integer into a variable of type any, then perform successful int and unsuccessful string assertions.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Type Assertions in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.