Home > database >  Golang set reflect.Value by sql.NullString
Golang set reflect.Value by sql.NullString

Time:11-03

How can I set item.SourceId(the type is sql.NullString) by inData.SourceId(the type is String) ? I don't know how to write the code in the red block enter image description here

I found reflect.ValueOf(&foo).Elem().Field(0).SetInt(321) in Using reflect, how do you set the value of a struct field?. Is there something like SetInt for sql.NullString ?

   type InDataType struct {
        Id          string  
        SourceId    string
    }

    type ItemType struct {
        Id          string      
        SourceId    sql.NullString 
    }

setField(item, inData, "SourceId")


func setField(item interface{}, inData interface{}, fieldName string) {
    // t := reflect.TypeOf(inData)
    // fmt.Println(t)
    itemValue := reflect.ValueOf(item).Elem().FieldByName(fieldName)
    itemType := reflect.ValueOf(item).Elem().FieldByName(fieldName).Type().String()
    fmt.Println(itemType, ",", itemValue)

    inDataValue := reflect.ValueOf(inData).Elem().FieldByName(fieldName)
    inDataType := reflect.ValueOf(inData).Elem().FieldByName(fieldName).Type().String()
    fmt.Println(inDataType, ",", inDataValue)
    if itemType == "sql.NullString" {
        // itemValue = sql.NullString{String: inDataValue.Value().String(), Valid: inDataValue.String() != ""}

    }
}

CodePudding user response:

if itemType == "sql.NullString" {
    itemValue.Set(reflect.ValueOf(sql.NullString{String: inDataValue.String(), Valid: inDataValue.String() != ""}))
}
  • Related