

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 3
click for more info
Not enough gems
Cost: 6 gems
1: Interfaces in Go
incomplete
2: Interface Implementation
incomplete
3: Interfaces Are Implemented Implicitly
incomplete
4: Interfaces Quiz
incomplete
5: Multiple Interfaces
incomplete
6: Name Your Interface Parameters
incomplete
7: Type Assertions in Go
incomplete
8: Type Switches
incomplete
9: Clean Interfaces
incomplete
10: Message Formatter
incomplete
11: Process Notifications
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
A type switch makes it easy to do several type assertions in a series.
A type switch is similar to a regular switch statement, but the cases specify types instead of values.
func printNumericValue(num interface{}) {
switch v := num.(type) {
case int:
fmt.Printf("%T\n", v)
case string:
fmt.Printf("%T\n", v)
default:
fmt.Printf("%T\n", v)
}
}
func main() {
printNumericValue(1)
// prints "int"
printNumericValue("1")
// prints "string"
printNumericValue(struct{}{})
// prints "struct {}"
}
fmt.Printf("%T\n", v) prints the type of a variable.
After submitting our last snippet of code for review, a more experienced gopher told us to use a type switch instead of successive assertions. Let's make that improvement!
Implement the getExpenseReport function using a type switch.