【问题标题】:How do I print that the type of a variable is interface {}如何打印变量的类型是 interface {}
【发布时间】: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


【解决方案1】:

如何将 j 的类型打印为 interface {} ?

你不能。

来源:fmt 文档:

不管动词如何,如果操作数是接口值,则使用内部具体值,而不是接口本身。

您为什么会对拼写“interface{}”感兴趣? fmt 包的这种行为使其可以立即处理任何类型,而无需特殊魔法。

@mkopriva的例子中:

fmt.Println(reflect.TypeOf((*interface{})(nil)).Elem())

输出是interface {},因为那是*interface{}元素类型的字符串表示,实际上是interface {}。但在这种情况下,您是通过反射而不是 fmt 动词到达那里的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-03
    • 2023-03-26
    • 2014-07-23
    • 2016-08-10
    • 1970-01-01
    相关资源
    最近更新 更多