-2

Is there a way to access struct fields of type []byte with a string?

package main

import "fmt"
import "reflect"

type myStruct struct {
    string1 []byte
    string2 []byte
}

func main() {
    v := myStruct{[]byte("text"), []byte("text2")}
    fmt.Println(getField(&v, "string1"))
}

func getField(v *myStruct, field string) string {
    r := reflect.ValueOf(v)
    f := reflect.Indirect(r).FieldByName(field)
    return f.String()
}

In my example, the output string is: <[]uint8 Value>

I've already read the following examples, but these only access int or string values.

Access struct property by name

https://socketloop.com/tutorials/golang-how-to-get-struct-field-and-value-by-name

1 Answers1

0

package main

import "fmt"
import "reflect"

type myStruct struct {
    string1 []byte
    string2 []byte
}

func main() {
    v := myStruct{[]byte("text"), []byte("text2")}
    fmt.Println(getField(&v, "string1"))
}

func getField(v *myStruct, field string) string {
    r := reflect.ValueOf(v)
    f := reflect.Indirect(r).FieldByName(field)
    return string(f.Bytes())
}
Dmitry Harnitski
  • 5,838
  • 1
  • 28
  • 43