在golang中,interface{}允许接纳任意值,类似于Java中的Object类型。

可以直接用switch value.(type) 来判断类型,如:

type Test struct {
	Test string
}

func test(value interface{}) {
	switch value.(type) {
	case string:
		// 将interface转为string字符串类型
		fmt.Println("value type is string")
	case int32:
		// 将interface转为int32类型
		fmt.Println("value type is int32")
	case int64:
		// 将interface转为int64类型
		fmt.Println("value type is int64")
	case Test:
		// 将interface转为Test struct类型
		fmt.Println("value type is Test struct")
	case []int:
		// 将interface转为切片类型
		fmt.Println("value type is Test []int")
	default:
		fmt.Println("unknown")
	}
}

如果是单类型判断和转换可以用 v , ok = value.(type) 来判断和转换。

  • v:转换后的值
  • ok:是否转换成功,如果类型不对,返回false
  • value:interface{}变量
  • type:需要转换的类型,如:string、int32、int64、float64等等

如interface{}转string:

func test(value interface{}) {

	if op, ok := value.(string); ok {
		fmt.Println("value type is string:", op)
	} else {
		fmt.Println("value type is not string")
	}
}