Merge pull request #99 from skrul/type-switch
Complete type switch TODO
This commit is contained in:
commit
bee8f55277
@ -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"))
|
||||
}
|
||||
|
@ -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
|
||||
|
Loading…
x
Reference in New Issue
Block a user