vendredi 9 octobre 2015

How to reflect a typed slice of bytes? []byte

I'm trying to detect if an interface{} is of type []byte or is a typed value with the underlying value of type byte. I can do type assertion for the former but I can't find a solution for the latter. reflect reports its kind as uint8.

package main

import (
    "fmt"
    "reflect"
)

type xb []byte

func main() { 
    var x []byte
    if isByte(interface{}(x)){
        fmt.Printf("%v is byte\n", x)
    }
    var y xb
    if isByte(interface{}(y)){
        fmt.Printf("%v is byte\n", y)
    } 
}

// returns true if in is a slice of bytes.
func isByte(in interface{}) bool {
    _, ok := in.([]byte)
    if ok {
        return true
    }
    if reflect.TypeOf(in).Kind() != reflect.Slice {
        return false
    }
    fmt.Printf("Unknown %v\n", reflect.TypeOf(in).Elem().Kind())
    return false
}





Aucun commentaire:

Enregistrer un commentaire