github.com/zach-klippenstein/go@v0.0.0-20150108044943-fcfbeb3adf58/test/typeswitch1.go (about)

     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 on basic types.
     8  
     9  package main
    10  
    11  import "fmt"
    12  
    13  const (
    14  	a = iota
    15  	b
    16  	c
    17  	d
    18  	e
    19  )
    20  
    21  var x = []int{1, 2, 3}
    22  
    23  func f(x int, len *byte) {
    24  	*len = byte(x)
    25  }
    26  
    27  func whatis(x interface{}) string {
    28  	switch xx := x.(type) {
    29  	default:
    30  		return fmt.Sprint("default ", xx)
    31  	case int, int8, int16, int32:
    32  		return fmt.Sprint("signed ", xx)
    33  	case int64:
    34  		return fmt.Sprint("signed64 ", int64(xx))
    35  	case uint, uint8, uint16, uint32:
    36  		return fmt.Sprint("unsigned ", xx)
    37  	case uint64:
    38  		return fmt.Sprint("unsigned64 ", uint64(xx))
    39  	case nil:
    40  		return fmt.Sprint("nil ", xx)
    41  	}
    42  	panic("not reached")
    43  }
    44  
    45  func whatis1(x interface{}) string {
    46  	xx := x
    47  	switch xx.(type) {
    48  	default:
    49  		return fmt.Sprint("default ", xx)
    50  	case int, int8, int16, int32:
    51  		return fmt.Sprint("signed ", xx)
    52  	case int64:
    53  		return fmt.Sprint("signed64 ", xx.(int64))
    54  	case uint, uint8, uint16, uint32:
    55  		return fmt.Sprint("unsigned ", xx)
    56  	case uint64:
    57  		return fmt.Sprint("unsigned64 ", xx.(uint64))
    58  	case nil:
    59  		return fmt.Sprint("nil ", xx)
    60  	}
    61  	panic("not reached")
    62  }
    63  
    64  func check(x interface{}, s string) {
    65  	w := whatis(x)
    66  	if w != s {
    67  		fmt.Println("whatis", x, "=>", w, "!=", s)
    68  		panic("fail")
    69  	}
    70  
    71  	w = whatis1(x)
    72  	if w != s {
    73  		fmt.Println("whatis1", x, "=>", w, "!=", s)
    74  		panic("fail")
    75  	}
    76  }
    77  
    78  func main() {
    79  	check(1, "signed 1")
    80  	check(uint(1), "unsigned 1")
    81  	check(int64(1), "signed64 1")
    82  	check(uint64(1), "unsigned64 1")
    83  	check(1.5, "default 1.5")
    84  	check(nil, "nil <nil>")
    85  }