reflection - 反射(reflect) []byte 的值

标签 reflection go

如何获取此接口(interface)的 []byte 值?

package main

import (
    "reflect"
)

func byteInterface() interface{} {
    return []byte("foo")
}

func main() {
    //var b []byte
    i := byteInterface()

    switch {
    case reflect.TypeOf(i).Kind() == reflect.Slice && (reflect.TypeOf(i) == reflect.TypeOf([]byte(nil))):

    default:
        panic("should have bytes")
    }
}

最佳答案

您可以使用 type assertion为了这;无需使用 reflect 包:

package main

func byteInterface() interface{} {
    return []byte("foo")
}

func main() {
    i := byteInterface()

    if b, ok := i.([]byte); ok {
      // use b as []byte
      println(len(b))
    } else {
      panic("should have bytes")
    }
}

关于reflection - 反射(reflect) []byte 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27710022/

相关文章:

c++ - 检查c++中是否存在函数时出现问题

reflection - 避免反射 - 我怎样才能最好地重构这段代码?

python - 如何使 Python 模块中的变量在 Go 中可用?

types - 在 go 中,当 *Type 调用方法时如何创建接口(interface)?

object - Kotlin 中如何知道对象是否是单例?

c# - 使用 PropertyDescriptor 可以确定属性是否在当前类中被覆盖

json - 解码 JSON 并区分丢失的键和空值

go - 在 goroutine 中等待主线程 sleep

templates - 转到模板 : two or more slices ranges

c# - 通过反射获取属性类型