mardi 16 août 2022

Assigning to type alias using reflection in Go

I have setup a type called Provider that aliases an integer:

type Provider int

func (enum *Provider) Scan(raw interface{}) error {
    *enum = Provider(int(raw))
}

If I create an object, Foo, with a Provider field, like this:

type Foo struct {
    Code Provider
    Value string
}

foo := &Foo {
    Code:  Provider(0),
    Value: "derp",
}

var scnr sql.Scanner
scannerType := reflect.TypeOf(&scnr).Elem()

tType := reflect.TypeOf(foo)
tField := tType.Field(0)
fmt.Printf("Field %s, of type %s, kind %s\n", 
    tField.Name, tField.Type, tField.Type.Kind())

When I run this code, I get that the field is of type Provider and its Kind is int. However, I cannot assign an int to a Provider using reflection because this will fail:

fValue := reflect.ValueOf(foo).Elem()
vField := fValue.Field(0)
vField.Set(reflect.ValueOf(1)) // panic: reflect.Set: value of type int is not assignable to type Provider

Is there a way I can make this work?





Aucun commentaire:

Enregistrer un commentaire