【发布时间】:2022-01-25 10:10:11
【问题描述】:
package main
import (
"fmt"
"reflect"
)
func main() {
fmt.Println("doing typeSwitchFunc(nil):")
typeSwitchFunc(nil)
fmt.Println("\ndoing typeSwitchFunc(22):")
typeSwitchFunc(22)
}
func typeSwitchFunc(i interface{}) {
switch j := i.(type) {
case nil:
// How do I print the type of j as interface{} ? Below only gives me the information on underlying type stored in j -- (A)
fmt.Printf("case nil: j is type %T, j value %v, i is type %T, i value %v\n", j, j, i, i)
fmt.Printf("case nil: j is type: %v, j value: %v, j kind: %v\n", reflect.TypeOf(j), reflect.ValueOf(j), reflect.ValueOf(j).Kind())
default:
// How do I print the type of j as interface{} ? Below only gives me the information on underlying type stored in j -- (B)
fmt.Printf("default: j is type %T, j value %v, i is type %T, i value %v\n", j, j, i, i)
fmt.Printf("default: j is type: %v, j value: %v, j kind: %v\n", reflect.TypeOf(j), reflect.ValueOf(j), reflect.ValueOf(j).Kind())
}
}
输出:
$ go run type-switch-minimal-example.go
doing typeSwitchFunc(nil):
case nil: j is type <nil>, j value <nil>, i is type <nil>, i value <nil>
case nil: j is type: <nil>, j value: <invalid reflect.Value>, j kind: invalid
doing typeSwitchFunc(22):
default: j is type int, j value 22, i is type int, i value 22
default: j is type: int, j value: 22, j kind: int
$ go version
go version go1.17.4 darwin/amd64
如何将j 的类型打印为interface {}?
【问题讨论】:
-
只有当你有一个指向 the-interface-i-want-to-print 的指针时,你才能使用反射:go.dev/play/p/hkzxp7-QN5l
-
如果你真的想要这样的结果,你可以做类似
fmt.Printf("%s", "interface{}")的事情。
标签: go