| 1 |
// run |
| 2 |
|
| 3 |
// Copyright 2009 The Go Authors. All rights reserved. |
| 4 |
// Use of this source code is governed by a BSD-style |
| 5 |
// license that can be found in the LICENSE file. |
| 6 |
|
| 7 |
// Test simple type switches, including chans, maps etc. |
| 8 |
|
| 9 |
package main |
| 10 |
|
| 11 |
import "os" |
| 12 |
|
| 13 |
const ( |
| 14 |
Bool = iota |
| 15 |
Int |
| 16 |
Float |
| 17 |
String |
| 18 |
Struct |
| 19 |
Chan |
| 20 |
Array |
| 21 |
Map |
| 22 |
Func |
| 23 |
Last |
| 24 |
) |
| 25 |
|
| 26 |
type S struct { |
| 27 |
a int |
| 28 |
} |
| 29 |
|
| 30 |
var s S = S{1234} |
| 31 |
|
| 32 |
var c = make(chan int) |
| 33 |
|
| 34 |
var a = []int{0, 1, 2, 3} |
| 35 |
|
| 36 |
var m = make(map[string]int) |
| 37 |
|
| 38 |
func assert(b bool, s string) { |
| 39 |
if !b { |
| 40 |
println(s) |
| 41 |
os.Exit(1) |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
func f(i int) interface{} { |
| 46 |
switch i { |
| 47 |
case Bool: |
| 48 |
return true |
| 49 |
case Int: |
| 50 |
return 7 |
| 51 |
case Float: |
| 52 |
return 7.4 |
| 53 |
case String: |
| 54 |
return "hello" |
| 55 |
case Struct: |
| 56 |
return s |
| 57 |
case Chan: |
| 58 |
return c |
| 59 |
case Array: |
| 60 |
return a |
| 61 |
case Map: |
| 62 |
return m |
| 63 |
case Func: |
| 64 |
return f |
| 65 |
} |
| 66 |
panic("bad type number") |
| 67 |
} |
| 68 |
|
| 69 |
func main() { |
| 70 |
for i := Bool; i < Last; i++ { |
| 71 |
switch x := f(i).(type) { |
| 72 |
case bool: |
| 73 |
assert(x == true && i == Bool, "bool") |
| 74 |
case int: |
| 75 |
assert(x == 7 && i == Int, "int") |
| 76 |
case float64: |
| 77 |
assert(x == 7.4 && i == Float, "float64") |
| 78 |
case string: |
| 79 |
assert(x == "hello" && i == String, "string") |
| 80 |
case S: |
| 81 |
assert(x.a == 1234 && i == Struct, "struct") |
| 82 |
case chan int: |
| 83 |
assert(x == c && i == Chan, "chan") |
| 84 |
case []int: |
| 85 |
assert(x[3] == 3 && i == Array, "array") |
| 86 |
case map[string]int: |
| 87 |
assert(x != nil && i == Map, "map") |
| 88 |
case func(i int) interface{}: |
| 89 |
assert(x != nil && i == Func, "fun") |
| 90 |
default: |
| 91 |
assert(false, "unknown") |
| 92 |
} |
| 93 |
} |
| 94 |
|
| 95 |
// boolean switch (has had bugs in past; worth writing down) |
| 96 |
switch { |
| 97 |
case true: |
| 98 |
assert(true, "switch 2 bool") |
| 99 |
default: |
| 100 |
assert(false, "switch 2 unknown") |
| 101 |
} |
| 102 |
|
| 103 |
switch true { |
| 104 |
case true: |
| 105 |
assert(true, "switch 3 bool") |
| 106 |
default: |
| 107 |
assert(false, "switch 3 unknown") |
| 108 |
} |
| 109 |
|
| 110 |
switch false { |
| 111 |
case false: |
| 112 |
assert(true, "switch 4 bool") |
| 113 |
default: |
| 114 |
assert(false, "switch 4 unknown") |
| 115 |
} |
| 116 |
} |