mardi 14 avril 2020

How to get raw type from reflect slice

I want to check table reference field exist, that take the struct to ormer query table. The VaildData function take diffrent struct or slice and beego orm.NewOrm().Read(v) of v that only vaild pointer struct.

func VaildData(cols ...interface{}) (err error) {
    for _, col := range cols {
        value := reflect.ValueOf(col)
        switch reflect.TypeOf(col).Kind() {
        case reflect.Slice:
            if length := value.Len(); length > 0 {
                for i := 0; i < length; i++ {
                    logs.Info("slice is %v", value.Index(i).Elem().Type().Name())
                    t := value.Index(i).Elem().Type()
                    a := value.Index(i).Interface().(t)
                    err = Ormer().Read(a)
                    if err != nil {
                        return err
                    }
                }
            }
        case reflect.Ptr:
            logs.Info(value)
            t := value.Interface().Type()
            err = Ormer().Read(value.Interface().(t))
            if err != nil {
                return err
            }
        default:
            return fmt.Errorf("invalid collection type, need pointer or slice pointer %s", reflect.ValueOf(col))
        }


    }
    return nil
}


type Cluster struct {
    ID int
    Name string
    Environments []*Environment
    Region *Region
}

type Environment struct {
    ID int
    Name string
}

type Region struct {
   ID int
   Name string
}

c := Cluster{}
err := VaildData(c.Environments, c.Region)

but that does not work, it excpet error.

t is not a type




Aucun commentaire:

Enregistrer un commentaire