Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflect value of []byte

Tags:

reflection

go

How do I retrieve the []byte value of this interface?

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")
    }
}
like image 685
kwolfe Avatar asked Dec 30 '14 17:12

kwolfe


People also ask

What is reflect value?

Reflection is provided by the reflect package. It defines two important types, Type and Value . A Type represents a Go type. It is an interface with many methods for discriminating among types and inspecting their components, like the fields of a struct or the parameters of a function.

What is reflect in Go?

Reflection is the ability of a program to introspect and analyze its structure during run-time. In Go language, reflection is primarily carried out with types. The reflect package offers all the required APIs/Methods for this purpose. Reflection is often termed as a method of metaprogramming.

What is reflect indirect?

The reflect. Indirect() Function in Golang is used to get the value that v points to, i.e., If v is a nil pointer, Indirect returns a zero Value. If v is not a pointer, Indirect returns v. To access this function, one needs to imports the reflect package in the program.


1 Answers

You can use a type assertion for this; no need to use the reflect package:

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")
    }
}
like image 173
Tim Cooper Avatar answered Oct 02 '22 22:10

Tim Cooper