Заполнить структуру дефолтными значениями в go

Есть функция:

update(v interface{}, updates map[string]interface{})

v — произвольная структура (модель в БД).

Задача пройтись по всем полям и заполнить их значениями из map[string]interface{}. Предполагается, что interface{} совпадает с типом поля, которое является ключом в map[string]interface{}


Ответы (1 шт):

Автор решения: hedgehogues
// setField sets value to a struct's field by field's value
// field is field of struct
// value is value to set to the struct
func setField(field reflect.Value, value interface{}) {
    t := field.Type()
    p := unsafe.Pointer(field.UnsafeAddr())
    v := reflect.ValueOf(value)
    reflect.NewAt(t, p).Elem().Set(v)
}


// update updates pStructure by default_ values where key is field name of pStructure, value of map is value of
// structure by concrete field. structure and pStructure are the struct and pointer to struct respectively
func update(structure interface{}, pStructure interface{}, default_ map[string]interface{}) {
    // TODO: change pointer to interface and interface to single object
    t := reflect.TypeOf(structure)
    for i := 0; i < t.NumField(); i++ {
        fName := t.Field(i).Name
        defaultValue, ok := default_[fName]
        if ok {
            value := reflect.ValueOf(pStructure).Elem()
            field := value.FieldByName(fName)
            setField(field, defaultValue)
        }
    }
}

Альтернативным подходом является использование этой библиотеки

→ Ссылка