Module lessons (3/5)
Type switch
A type switch discriminates among multiple possible types of an
interface value. It's the generalization of comma ok when there are
more than one case.
Syntax
func describe(i interface{}) string {
switch v := i.(type) {
case int:
return fmt.Sprintf("int %d", v)
case string:
return fmt.Sprintf("string %q", v)
case nil:
return "nil"
default:
return fmt.Sprintf("altro tipo: %T", v)
}
}i.(type)is a special syntax, valid ONLY insideswitch.v := ...binds the value with the current case's type: insidecase int,vhas typeint.defaultcatches all other types; therevhas the type of the original interface.case nilmatches the interface with a nil dynamic type.
"Nameless" case
If you don't need the typed value, you can omit the v:
switch i.(type) {
case int:
// you know it's an int, but you don't have a variable of that type
case string:
// ...
}A form used when you just need to discriminate the type, not operate on the value.
Multiple types in the same case
switch v := i.(type) {
case int, int64:
// here v is still interface{}: the "common" type is just the interface
fmt.Println("numero intero:", v)
case string:
// here v is string
fmt.Println("stringa:", v)
}Typical use case: formatted printing
func print(i interface{}) {
switch v := i.(type) {
case int:
fmt.Printf("%d\n", v)
case string:
fmt.Printf("%s\n", v)
case fmt.Stringer:
fmt.Println(v.String())
default:
fmt.Printf("%v\n", v)
}
}fmt.Println itself uses a type switch internally to handle the
standard formats.
Type switch vs reflection
For a few known types → type switch (fast, readable).
For dynamic inspection of unknown types → the reflect package (more
powerful but slower and more verbose).
Try it
Implement describe(i interface{}) string that returns 'int', 'string' or 'altro' depending on the dynamic type.
Show hint
Syntax: `switch i.(type) { case T: ... default: ... }`.
Solution available after 3 attempts
Write printVal(i interface{}) that uses v := i.(type) and prints with %d for int, %s for string.
Show hint
Inside `case int`, v has type int (you can pass it to Printf).
Solution available after 3 attempts
Which syntax starts a type switch?
switch ??? {
case int: ...
}Recap
switch v := i.(type) { case T: ... }: discriminates on the dynamic type.- Inside a single-type case,
vhas the case's type. case T1, T2:vkeeps the original interface's type.defaultfor unhandled cases;case nilfor the nil interface.- No
fallthroughin type switches. - 1 type → type assertion; 2+ types → type switch.