美文网首页
Go语言 类型转换,类型断言,类型开关

Go语言 类型转换,类型断言,类型开关

作者: 小杰的快乐时光 | 来源:发表于2018-08-18 22:49 被阅读0次

    类型转换
    Go语言中提供了一种不同类型但是相互兼容的可以相互转换的方式,这种方式是非常有用且安全的。非数值间相互转换不会丢失精度,数值间相互转换就需要考虑精度可能丢失的情况。
    string,int,float类型转换

    //string到int
    int,err:=strconv.Atoi(string)
    //string到int64
    int64, err := strconv.ParseInt(string, 10, 64)
    //int到string
    string:=strconv.Itoa(int)  等价于 s := strconv.FormatInt(int64(i), 10)
    //int64到string
    string:=strconv.FormatInt(int64,10)
    //string到float32(float64)
    float,err := strconv.ParseFloat(string,32/64)
    //float到string
    string := strconv.FormatFloat(float32, 'E', -1, 32)
    string := strconv.FormatFloat(float64, 'E', -1, 64)
    

    类型断言
    在处理外部源接收到的数据,想要创建一个通用函数及在进行面向对象编程时,我们会需要使用interface{}类型。我们可以使用类型断言将一个interface{}类型的值转换为实际数据的值。
    使用类型断言有以下两种方式

    ① 安全类型断言
    resultType,boolean := expression.(Type) 
    ②非安全类型断言,失败时会panic()
    resultType,boolean := expression.(Type) 
    

    实例

    func main() {
       var a interface{} = 1
       var b interface{} = "abc"
       c,bool:= a.(int)
       d := b.(string)
       fmt.Println(c,bool)
       fmt.Println(d)
    }
    -----output-----
    1 true
    abc
    

    类型开关
    如果变量类型是许多类型中的一种,那么我们使用switch配合interface{}来筛选

    func classifier(items ...interface{})  {
       for i,x := range items {
          switch x.(type) {
          case bool:
             fmt.Printf("type #%d is bool",i)
          case float64:
             fmt.Printf("type #%d is float64",i)
          case string:
             fmt.Printf("type #%d is string",i)
          case int:
             fmt.Printf("type #%d is int",i)
          default:
             fmt.Printf("type is unknow")
          }
       }
    }
    

    相关文章

      网友评论

          本文标题:Go语言 类型转换,类型断言,类型开关

          本文链接:https://www.haomeiwen.com/subject/xjsqiftx.html