From b78645279c4b86508e281d40da52f4858bb997a5 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Tue, 22 Jul 2014 13:32:22 +0800 Subject: [PATCH] Simplify set field value --- utils.go | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/utils.go b/utils.go index d1587660..a9091aeb 100644 --- a/utils.go +++ b/utils.go @@ -8,7 +8,6 @@ import ( "reflect" "regexp" "runtime" - "strconv" "strings" "sync" ) @@ -123,25 +122,19 @@ func fileWithLineNum() string { return "" } -func setFieldValue(field reflect.Value, value interface{}) bool { +func setFieldValue(field reflect.Value, value interface{}) (result bool) { + result = false if field.IsValid() && field.CanAddr() { - switch field.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - if str, ok := value.(string); ok { - value, _ = strconv.Atoi(str) - } - field.SetInt(reflect.ValueOf(value).Int()) - default: - if scanner, ok := field.Addr().Interface().(sql.Scanner); ok { - scanner.Scan(value) - } else { - field.Set(reflect.ValueOf(value)) - } + result = true + if scanner, ok := field.Addr().Interface().(sql.Scanner); ok { + scanner.Scan(value) + } else if reflect.TypeOf(value).ConvertibleTo(field.Type()) { + field.Set(reflect.ValueOf(value).Convert(field.Type())) + } else { + result = false } - return true } - - return false + return } func isBlank(value reflect.Value) bool {