Go 类型转换与类型判断

Go 类型转换与类型判断

1.类型转化

T(a) :

  • T 是目标类型
  • a 是源变量
package main

import "fmt"

// go语言的类型转化

func main() {
	var foo = 1
	str:= string(foo)
	fmt.Printf("%T",str)
}

2.类型判断

x.(T) :

  • x判断的变量
  • T 目标类型

第一种方式:

	_, ok1 := interface{}(a).([]string)

第二种方式:

func getElement(containerI interface{}) (elem string, err error) {
	switch t := containerI.(type) {
	case []string:
		elem = t[1]
	case map[int]string:
		elem = t[1]
	default:
		err = fmt.Errorf("unsupported container type: %T", containerI)
		return
	}
	return
}
posted @ 2020-09-04 15:33  sixinshuier  阅读(516)  评论(0编辑  收藏  举报