Parcourir la source

exp - Improve struct formatting ease of use.

Rename FormatStruct to AppendStruct. Modify function to append to
existing slice instead of creating a new slice.
Gary Burd il y a 13 ans
Parent
commit
0e476adcff
2 fichiers modifiés avec 4 ajouts et 6 suppressions
  1. 1 1
      exp/scan/example.go
  2. 3 5
      exp/scan/struct.go

+ 1 - 1
exp/scan/example.go

@@ -21,7 +21,7 @@ func main() {
 
 	v0 := &MyStruct{1, "hello"}
 
-	_, err = c.Do("HMSET", append([]interface{}{"key"}, scan.FormatStruct(v0)...)...)
+	_, err = c.Do("HMSET", scan.AppendStruct([]interface{}{"key"}, v0)...)
 	if err != nil {
 		log.Fatal(err)
 	}

+ 3 - 5
exp/scan/struct.go

@@ -97,7 +97,7 @@ func ScanStruct(reply interface{}, dst interface{}) error {
 	return nil
 }
 
-func FormatStruct(src interface{}) []interface{} {
+func AppendStruct(args []interface{}, src interface{}) []interface{} {
 	v := reflect.ValueOf(src)
 	if v.Kind() == reflect.Ptr {
 		if v.IsNil() {
@@ -109,11 +109,9 @@ func FormatStruct(src interface{}) []interface{} {
 		panic("redigo: FormatStruct argument must be a struct or pointer to a struct")
 	}
 	ss := structSpecForType(v.Type())
-
-	result := make([]interface{}, 0, 2*len(ss.l))
 	for _, fs := range ss.l {
 		fv := v.FieldByIndex(fs.index)
-		result = append(result, fs.name, fv.Interface())
+		args = append(args, fs.name, fv.Interface())
 	}
-	return result
+	return args
 }