diff --git a/examples/switch/switch.go b/examples/switch/switch.go index e8ad843..fe95e63 100644 --- a/examples/switch/switch.go +++ b/examples/switch/switch.go @@ -40,6 +40,22 @@ func main() { default: fmt.Println("it's after noon") } -} -// todo: type switches + // A type `switch` compares types instead of values. You + // can use this to discover the the type of an interface + // value. In this example, the variable `t` will have the + // type corresponding to its clause. + whatAmI := func(i interface{}) string { + switch t := i.(type) { + case bool: + return "I am a bool" + case int: + return "I am an int" + default: + return fmt.Sprintf("Can't handle type %T", t) + } + } + fmt.Println(whatAmI(1)) + fmt.Println(whatAmI(true)) + fmt.Println(whatAmI("hey")) +} diff --git a/examples/switch/switch.sh b/examples/switch/switch.sh index 6a3343e..0d67c0b 100644 --- a/examples/switch/switch.sh +++ b/examples/switch/switch.sh @@ -2,3 +2,6 @@ $ go run switch.go write 2 as two it's the weekend it's before noon +I am an int +I am a bool +Can't handle type string