allthenutsandbolts
allthenutsandbolts

Reputation: 1523

Converting Value to a Struct

I have a Struct which is as follows

type pathObject struct {
    s      *gizmo.Session
    finals bool
    path   *path.Path
}

I'm getting this struct and I need to extract the path object but I keep getting an compilation error

Here is my code for conversion

r := reflect.ValueOf(v)

for i := 0; i < val.NumField(); i++ {
    valueField := val.Field(i)
    typeField := val.Type().Field(i)
    val.Interface()

    if typeField.Name == "path" {
        log.Printf("typeName %v\n", typeField.Name)
        log.Printf("value %v\n", valueField)

        f := reflect.Indirect(r).FieldByName("path")

        log.Printf("CanInterface %v\n", valueField.Elem())
        p := valueField.Elem().(path.Path)

        //patObject := reflect.Indirect(valueField).FieldByName("path")

    }
    //f := valueField.Interface()
    //val := reflect.ValueOf(f)
    //slog.Printf("default %v\n", val)
}

I get an compiltion error on this line p := valueField.Elem().(path.Path) saying

invalid type assertion: valueField.Elem().(path.Path) (non-interface type reflect.Value on left)

Any clues how I can get past the error and get it to convert?

Upvotes: 0

Views: 962

Answers (1)

Thundercat
Thundercat

Reputation: 121129

Assert the type on the result of calling the reflect.Value Interface() method. The Interface() method returns the actual value.

p := valueField.Elem().Interface().(path.Path)

The path field must be exported to access the value:

type pathObject struct {
    s      *gizmo.Session
    finals bool
    Path   *path.Path
}

Try this simpler code:

func getPath(v interface{}) *path.Path {
    r := reflect.Indirect(reflect.ValueOf(v))
    f := r.FieldByName("Path")
    return f.Interface().(*path.Path)
}

playground example

Upvotes: 2

Related Questions