go的interface assert

2022/3/8 6:46:55

本文主要是介绍go的interface assert,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

点击查看代码
package main

import "fmt"

func test(a interface{}){
	// 将接口类型的变量转化为具体类型 加个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(s)
		return 
	}
	str, ok := a.(string)
	if ok{
		fmt.Println(str)
		return 
	}
	f, ok := a.(float32)
	if ok{
		fmt.Println(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
}


// 缺点是要转2次
func testSeitch(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 testInterface2(){
	var a int =100
	testSeitch(a)

	var b  string = "hello "
	testSeitch(b)
}

// 更推荐使用这个
func testSeitch2(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
	testSeitch2(a)

	var b  string = "hello "
	testSeitch2(b)
}

func main() {
	testInterface1()
	testInterface2()
	testInterface3()
}

输出:

点击查看代码
100
0 can't vonvert to int
hello world
a is int, value :100
a is string, value :hello
a is int, value :100
a is string, value :hello


这篇关于go的interface assert的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程