• go 结构体类型反射 type_assert


    package main
    
    import "fmt"
    
    func test(a interface{}){
    	fmt.Printf("你好啊%#v==%v==%T==%p\n",a,a,a,&a)
    	// 将接口类型的变量转化为具体类型 加个OK 判断, 可以避免程序直接崩溃, ok=false 转行失败
    	s,ok := a.(int)  // 所以要加ok 判断, 对于不是int类型的, 会直接崩溃 panic: interface conversion: interface {} is string, not int
    	if !ok {
    		fmt.Printf("%v can't vonvert to int\n",s)
    	}
    	if ok {
    		fmt.Println("转化为int ok>>",s)
    		return 
    	}
    	str, ok := a.(string)
    	if ok{
    		fmt.Printf("%v 转化为str ok>>",str)
    		return 
    	}
    	f, ok := a.(float32)
    	if ok {
    		fmt.Println("转化为float ok>>",f)
    		return 
    	}
    	fmt.Println("can not define type of a")
    }
    
    
    func testInterface1(){
    	var a int =100
    	test(a)
    	var b string =  "hello world"
    	test(b)  //  panic: interface conversion: interface {} is string, not int
    }
    
    func testInterface2(){
    	var a int =100
    	testSwitch(a)
    
    	var b  string = "hello "
    	testSwitch(b)
    }
    
    // 缺点是要转2次
    func testSwitch(a interface{}){
    	switch a.(type){
    	case string:
    		fmt.Printf("a is string, value :%v\n",a.(string))
    	case int:
    		fmt.Printf("a is int, value :%v\n",a.(int))
    	case int32:
    		fmt.Printf("a is int32, value :%v\n",a.(int32))
    	default:
    		fmt.Println("not support type\n")
    	}
    }
    
    // 更推荐使用这个
    func testSwitch2(a interface{}){
    	switch v := a.(type){
    	case string:
    		fmt.Printf("a is string, value :%v\n",v)
    	case int:
    		fmt.Printf("a is int, value :%v\n",v)
    	case int32:
    		fmt.Printf("a is int32, value :%v\n",v)
    	default:
    		fmt.Println("not support type\n")
    	}
    }
    
    func testInterface3(){
    	var a int =100
    	testSwitch2(a)
    
    	var b  string = "hello "
    	testSwitch2(b)
    }
    
    func main() {
    	testInterface1()
    	testInterface2()
    	testInterface3()
    }
    

    输出:

    你好啊100==100==int==0xc0000361f0
    转化为int ok>> 100
    你好啊"hello world"==hello world==string==0xc000036210
    0 can't vonvert to int
    hello world 转化为str ok>>a is int, value :100
    a is string, value :hello
    a is int, value :100
    a is string, value :hello
    
  • 相关阅读:
    jsp页面中使用 splitfn:split注意事项
    【SQL】- 基础知识梳理(二)
    【SQL】- 基础知识梳理(一)
    面向对象编程思想-解释器模式
    NPOI操作Excel
    面向对象编程思想-备忘录模式
    面向对象编程思想-访问者模式
    面向对象编程思想-责任链模式
    面向对象编程思想-策略模式
    面向对象编程思想-状态模式
  • 原文地址:https://www.cnblogs.com/heris/p/16027549.html
Copyright © 2020-2023  润新知