golang断言与类型判断


golang断言

  • 一个interface 需要类型转换的时候,语法 i.(T)
  • v,ok:=i.(T) ,ok=true代表断言成功,ok=false v是这个类型的0值
package main

import "fmt"

func main() {

   var i interface{} = 10
   v, ok := i.(bool)
   fmt.Println(v, ok)
   v2 := i.(int)
   fmt.Println(v2)
}


/*
false false
10
*/

类型判断

package main

import "fmt"

func main() {

	var i interface{} = 10
	v, ok := i.(string)
	fmt.Println(v, ok)
	v2 := i.(int)
	fmt.Println(v2)

	switch i.(type) {
	case int:
		fmt.Println("int")
	case string:
		fmt.Println("string..")
	case bool:
		fmt.Println("bool")
	default:
		fmt.Println("eroor")
	}
}


/*
 false
10
int
*/

Author: 千里
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source 千里 !
  TOC