summaryrefslogtreecommitdiff
path: root/test/typeswitch.go
blob: 0a421ae96fbdb69226ffe43772ccd30ece49fc7d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// $G $F.go && $L $F.$A && ./$A.out

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import "os"

const (
	Bool = iota;
	Int;
	Float;
	String;
	Struct;
	Chan;
	Array;
	Map;
	Func;
	Last;
)

type S struct { a int }
var s S = S{1234}

var c = make(chan int);

var a	= []int{0,1,2,3}

var m = make(map[string]int)

func assert(b bool, s string) {
	if !b {
		println(s);
		os.Exit(1);
	}
}

func f(i int) interface{} {
	switch i {
	case Bool:
		return true;
	case Int:
		return 7;
	case Float:
		return 7.4;
	case String:
		return "hello";
	case Struct:
		return s;
	case Chan:
		return c;
	case Array:
		return a;
	case Map:
		return m;
	case Func:
		return f;
	}
	panic("bad type number");
}

func main() {
	for i := Bool; i < Last; i++ {
		switch x := f(i).(type) {
		case bool:
			assert(x == true && i == Bool, "bool");
		case int:
			assert(x == 7 && i == Int, "int");
		case float:
			assert(x == 7.4 && i == Float, "float");
		case string:
			assert(x == "hello"&& i == String, "string");
		case S:
			assert(x.a == 1234 && i == Struct, "struct");
		case chan int:
			assert(x == c && i == Chan, "chan");
		case []int:
			assert(x[3] == 3 && i == Array, "array");
		case map[string]int:
			assert(x == m && i == Map, "map");
		case func(i int) interface{}:
			assert(x == f && i == Func, "fun");
		default:
			assert(false, "unknown");
		}
	}

	// boolean switch (has had bugs in past; worth writing down)
	switch {
	case true:
		assert(true, "switch 2 bool");
	default:
		assert(false, "switch 2 unknown");
	}

	switch true {
	case true:
		assert(true, "switch 3 bool");
	default:
		assert(false, "switch 3 unknown");
	}

	switch false {
	case false:
		assert(true, "switch 4 bool");
	default:
		assert(false, "switch 4 unknown");
	}

}