lundi 12 mars 2018

Reflect on struct passed into interface{} in function parameter - Golang

I pass struct into a function as interface{}. Then inside I work with it using reflect to get the struct attributes. Here's the code:

func (db *DB) Migrate(domain ...interface{}) {
    // statement := "CREATE TABLE IF NOT EXISTS %s (%s, %s, %s, %s, %s)"
    for _,i := range domain {
        params := BindStruct(&i)
        statement := CreateStatement("create", len(params))
        _,err := db.Exec(fmt.Sprintf(statement, params...))
        if err != nil {
            log.Fatal("Error migrating database schema - ", err)
            break
        }
    }
} 

func BindStruct(domain interface{}) (params []interface{}) {
    tableName := reflect.TypeOf(domain).Elem().Name()
    params = append(params, tableName)

    val := reflect.ValueOf(domain).Elem()
    for i:=0; i < val.NumField(); i++ {
        field := val.Type().Field(i)
        tag := field.Tag

        fieldName := field.Name
        fieldType := tag.Get("sql_type")
        fieldTags := tag.Get("sql_tag")

        paramstring := fieldName + " " + fieldType + " " + fieldTags
        params = append(params, paramstring)
    }
    return params
}

I got an error on the line for i:=0; i < val.NumField(); i++ { in BindStruct function. The error message is:

panic: reflect: call of reflect.Value.NumField on interface Value

If I remove & from params := BindStruct(&i) becoming params := BindStruct(i) in Migrate function, I got this error:

panic: runtime error: invalid memory address or nil pointer

dereference[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x4ff457]

What gives?





Aucun commentaire:

Enregistrer un commentaire