Type switches in Go
One switch over the dynamic type inside an interface value.
func describe(value any) string {
switch typed := value.(type) {
case nil:
return "nothing"
case int:
return fmt.Sprintf("int %d", typed*2)
case string:
return "string " + strings.ToUpper(typed)
case []int:
return fmt.Sprintf("%d ints", len(typed))
case error:
return "error " + typed.Error()
default:
return fmt.Sprintf("something else: %T", typed)
}
}
How it works
switch v := x.(type)binds v with the case's type.- A nil case catches an interface holding nothing.
- The default arm is what keeps it honest.
Keywords and builtins used here
anycasedefaulterrorfuncintlenreturnstringswitchtype
The run, in numbers
- Lines
- 16
- Characters to type
- 353
- Tokens
- 89
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 51 seconds.
Step 1 of 2 in Dynamic types, step 8 of 19 in Interfaces & generics.