
没有实例的 TypeOf:将结果传递给函数
在 Go 中,无需实例也可以获取“Type”那种类型的。这可以通过使用 Reflect.TypeOf() 来实现,但通常示例涉及实例。
在没有实例的情况下获取类型
在没有实例的情况下获取“类型”在一个实例中,技巧是从指向类型的指针开始,可以为该类型分配“类型化”nil。随后,.Elem() 可用于获取指向类型的reflect.Type 描述符,称为基类型。
1 2 3 4 5 6 7 8 | <code class = "go" >t := reflect.TypeOf((*int)(nil)).Elem()
fmt.Println(t)
t = reflect.TypeOf((*http.Request)(nil)).Elem()
fmt.Println(t)
t = reflect.TypeOf((*os.File)(nil)).Elem()
fmt.Println(t)</code>
|
登录后复制
示例输出:
传递类型
如果您需要传递类型并在开关中使用它们,请创建它们并将其存储在全局变量中以供参考:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <code class = "go" > var (
intType = reflect.TypeOf((*int)(nil))
httpRequestType = reflect.TypeOf((*http.Request)(nil))
osFileType = reflect.TypeOf((*os.File)(nil))
int64Type = reflect.TypeOf((*uint64)(nil))
)
func printType(t reflect.Type) {
switch t {
case intType:
fmt.Println( "Type: int" )
case httpRequestType:
fmt.Println( "Type: http.request" )
case osFileType:
fmt.Println( "Type: os.file" )
case int64Type:
fmt.Println( "Type: uint64" )
default :
fmt.Println( "Type: Other" )
}
}
func main() {
printType(intType)
printType(httpRequestType)
printType(osFileType)
printType(int64Type)
}</code>
|
登录后复制
简化方法
如果您仅将类型用于比较目的,请考虑使用常量而不是reflect.Type:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | <code class = "go" >type TypeDesc int
const (
typeInt TypeDesc = iota
typeHttpRequest
typeOsFile
typeInt64
)
func printType(t TypeDesc) {
switch t {
case typeInt:
fmt.Println( "Type: int" )
case typeHttpRequest:
fmt.Println( "Type: http.request" )
case typeOsFile:
fmt.Println( "Type: os.file" )
case typeInt64:
fmt.Println( "Type: uint64" )
default :
fmt.Println( "Type: Other" )
}
}
func main() {
printType(typeInt)
printType(typeHttpRequest)
printType(typeOsFile)
printType(typeInt64)
}</code>
|
登录后复制
以上是Go 中如何在没有实例的情况下获取类型?的详细内容。更多信息请关注PHP中文网其他相关文章!