反映[]字节的值

时间:2014-12-30 17:43:02

标签: reflection go

如何检索此接口的[]字节值?

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")
    }
}

1 个答案:

答案 0 :(得分:7)

您可以使用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")
    }
}