Go之类型判断

时间:2023-03-10 01:08:52
Go之类型判断
boy := util.Boy{util.Person{"Eric", 19, "boy"}, "1"}

var boyClone interface{} = boy

  如何判断 boyClone是否是boy类型呢?

if i, ok := boyClone.(util.Boy); ok {
fmt.Println(i)
}

如果判断多个类型,可以如下书写:

switch v := boyClone.(type) {

	case nil:
fmt.Println("nil")
case fmt.Stringer:
fmt.Println(v)
case func() string:
fmt.Println(v())
case util.Boy:
fmt.Println(v)
default:
fmt.Println("unknow")
}