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
    
  • 相关阅读:
    objectARX 获取ucs的X方向
    passivedns 安装指南
    sql server手工注入
    libimobiledevice安装步骤
    CAD系统变量(参数)大全
    objectARX判断当前坐标系
    access手工注入
    网站自动跳转
    python黑帽子源码
    objectarx 卸载加载arx模块
  • 原文地址:https://www.cnblogs.com/niuben/p/14814901.html
Copyright © 2011-2022 走看看