zoukankan      html  css  js  c++  java
  • golang interface 转 string、int、float64

    interface{}

    interface{} 接口、interface{} 类型很多人都会混淆。interface{} 类型是没有方法的接口。由于没有 implements 关键字,所以说所有的类型都至少实现了 0 个方法,所有类型都实现了空接口。这意味着,如果编写一个函数以 interface{} 值作为参数,那么你可以为该函数提供任何值。例如:

    func DoSomething(v interface{}) {
       // ...
    }
    

    第一种知道是什么类型

    如果知道是什么类型的话,就可以直接转

    // 假设 v 为 string或int64或float64
    func DoSomething(v interface{}) {
    	string1 := v.(string)
    	int1 := v.(int64)
    	float1 := v.(float64)
    }
    

    第二种不知道是什么类型

    这时候就可以使用类型断言,然后再转为具体类型

    func interface2Type(i interface{}) {
    	switch i.(type) {
    	case string:
    		fmt.Println("string", i.(string))
    		break
    	case int:
    		fmt.Println("int", i.(int))
    		break
    	case float64:
    		fmt.Println("float64", i.(float64))
    		break
    	}
    }
     
    func main() {
    	interface2Type("niuben")
    	interface2Type(1122)
    	interface2Type(11.22)
    }
    

    输出

    string niuben
    int 1122
    float64 11.22
    
  • 相关阅读:
    jedis操作redis事务练习
    jedis连接redis,测试操作redis常用的数据类型 String List Set Hash Zset
    多态的理解
    binarySeach方法
    数组重新认识
    String的 认识
    接口的 认识
    抽象类及抽象方法
    protected的深刻理解
    protected的认识
  • 原文地址:https://www.cnblogs.com/niuben/p/14814901.html
Copyright © 2011-2022 走看看