📜  GoLang 中的类型开关

📅  最后修改于: 2021-10-25 02:27:14             🧑  作者: Mango

switch是一种多路分支语句,用于代替多个 if-else 语句,但也可用于找出接口变量的动态类型。

类型开关是一种构造,它执行多个类型断言以确定变量的类型(而不是值)并运行指定类型的第一个匹配的 switch case。当我们不知道 interface{} 类型可能是什么时使用它。

示例 1:

// Golang program to illustrate the
// concept of type switches
package main
   
import (
    "fmt"
)
   
// main function
func main() {
       
    // an interface that has 
    // a string value
    var value interface{} = "GeeksforGeeks"
       
    // type switch to find 
    // out interface{} type
    switch t := value.(type){
       
        case int64:
  
            // if type is an integer
            fmt.Println("Type is an integer:", t)
  
        case float64:
  
            // if type is a floating point number
            fmt.Println("Type is a float:", t)
  
        case string:
  
            // if type is a string
            fmt.Println("Type is a string:", t)
  
        case nil:
  
            // if type is nil (zero-value)
            fmt.Println("Type is nil.")
  
        case bool:
  
            // if type is a boolean
            fmt.Println("Type is a bool:", t)
  
        default:
  
            // if type is other than above
            fmt.Println("Type is unkown!")
    }
}

输出:

Type is a string: GeeksforGeeks

开关可以有不同类型的多个值案例,并用于为许多类似案例选择一个公共代码块。

注意: Golang 不需要在 switch 中每个 case 的末尾有一个 ‘break’ 关键字。

示例 2:

// Golang program to illustrate the 
// concept of type switch with
// multiple value cases
package main
   
import (
    "fmt"
)
   
// function which implements type 
// switch with multiple cases value
func find_type(value interface{}) {
       
    // type switch to find 
    // out interface{} type
    switch t := value.(type) {
       
        case int, float64:
  
            // type is an int or float
            fmt.Println("Type is a number, either an int or a float:", t)
               
        case string, bool:
  
            // type is a string or bool
            fmt.Println("Type is either a string or a bool:", t)
               
        case *int, *bool:
  
            // type is either an int pointer
            // or a bool pointer
            fmt.Println("Type is a pointer to an int or a bool:", t)
               
        default:
  
            // type of the interface is unknown
            fmt.Println("Type unknown!")
    }
}
   
// main function
func main() {
       
    // an interface that has 
    // a string value
    var v interface{} = "GeeksforGeeks"
       
    // calling the find_type method
    // to determine type of interface
    find_type(v)
       
    // re-assigning v with a 
    // float64 value
    v = 34.55
       
    find_type(v)
}

输出:

Type is either a string or a bool: GeeksforGeeks
Type is a number, either an int or a float: 34.55