switch 介紹

語法

switch <expression> {
   case <expression>:
        fallthrough
     case <expression>:

     default:
}

// 進階語法
switch <simple statement>; <expression> {
   case <expression>:
     case <expression>:
     default:
}

package main

var (
    i interface{}
)

func convert(i interface{}) {
    switch t := i.(type) {
    caseint:
        println("i is interger", t)
    casestring:
        println("i is string", t)
    casefloat64:
        println("i is float64", t)
    default:
        println("type not found")
    }
}

func main() {
    i = 100
    convert(i)
    i = float64(45.55)
    convert(i)
    i = "foo"
    convert(i)
    convert(float32(10.0))
}

// 執行結果
i is interger 100
i is float64 +4.555000e+001
i is string foo
type not found