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.
7 // Test switch statements.
13 func assert(cond bool, msg string) {
15 print("assertion fail: ", msg, "\n")
83 assert(false, "default")
94 assert(false, "default")
111 assert(i5 == 5, "good")
158 assert(i5 == 5, "good")
166 fallthrough // tests scoping of cases
207 assert(i5 == 5, "good")
209 assert(fired, "fired")
244 assert(i5 == count, "good")
246 assert(fired, "fired")
250 assert(false, "wowie")
252 assert(true, "hello")
254 assert(false, "jumpn")
256 assert(false, "default")
260 switch i := i5 + 2; i {
264 assert(false, "fail")
268 // switch on nil-only comparison types
269 switch f := func() {}; f {
271 assert(false, "f should not be nil")
275 switch m := make(map[int]int); m {
277 assert(false, "m should not be nil")
281 switch a := make([]int, 1); a {
283 assert(false, "m should not be nil")
287 // switch on interface.
288 switch i := interface{}("hello"); i {
290 assert(false, `i should be "hello"`)
292 assert(true, "hello")
294 assert(false, `i should be "hello"`)
297 // switch on implicit bool converted to interface
298 // was broken: see issue 3980
299 switch i := interface{}(true); {
303 assert(false, "i should be true")
305 assert(false, "i should be true")
308 // switch on interface with constant cases differing by type.
309 // was rejected by compiler: see issue 4781
314 switch i := interface{}(float64(1.0)); i {
316 assert(false, "i should be float64(1.0)")
318 assert(false, "i should be float64(1.0)")
320 assert(false, "i should be float64(1.0)")
322 assert(false, "i should be float64(1.0)")
324 assert(false, "i should be float64(1.0)")
328 assert(false, "i should be float64(1.0)")
330 assert(false, "i should be float64(1.0)")
332 assert(false, "i should be float64(1.0)")
334 assert(false, "i should be float64(1.0)")
338 switch ar := [3]int{1, 2, 3}; ar {
339 case [3]int{1, 2, 3}:
340 assert(true, "[1 2 3]")
341 case [3]int{4, 5, 6}:
342 assert(false, "ar should be [1 2 3]")
344 assert(false, "ar should be [1 2 3]")
348 switch c1, c2 := make(chan int), make(chan int); c1 {
350 assert(false, "c1 did not match itself")
352 assert(false, "c1 did not match itself")
356 assert(false, "c1 did not match itself")
363 // empty switch with default case.
369 assert(fired, "fail")
371 // Default and fallthrough.
380 assert(count == 2, "fail")
382 // fallthrough to default, which is not at end.
393 assert(count == 2, "fail")
404 // Unified IR converts the tag and all case values to empty
405 // interface, when any of the case values aren't assignable to the
406 // tag value's type. Make sure that `case nil:` compares against the
407 // tag type's nil value (i.e., `(*int)(nil)`), not nil interface
408 // (i.e., `any(nil)`).
413 assert(false, "case any(nil) matched")
415 assert(false, "default matched")