mirror of
https://github.com/redis/go-redis.git
synced 2025-08-07 12:42:55 +03:00
Add ScanSlice.
This commit is contained in:
committed by
Vladimir Mihailenco
parent
6b8c6b3fe9
commit
681a1fe646
@@ -3,6 +3,7 @@ package proto
|
||||
import (
|
||||
"encoding"
|
||||
"fmt"
|
||||
"reflect"
|
||||
|
||||
"gopkg.in/redis.v5/internal"
|
||||
)
|
||||
@@ -105,3 +106,35 @@ func Scan(b []byte, v interface{}) error {
|
||||
"redis: can't unmarshal %T (consider implementing BinaryUnmarshaler)", v)
|
||||
}
|
||||
}
|
||||
|
||||
// Scan a string slice into a custom container
|
||||
// Example:
|
||||
// var container []YourStruct; ScanSlice([]string{""},&container)
|
||||
// var container []*YourStruct; ScanSlice([]string{""},&container)
|
||||
func ScanSlice(sSlice []string, container interface{}) error {
|
||||
val := reflect.ValueOf(container)
|
||||
|
||||
if !val.IsValid() {
|
||||
return fmt.Errorf("redis: ScanSlice(nil)")
|
||||
}
|
||||
|
||||
// Check the if the container is pointer
|
||||
if val.Kind() != reflect.Ptr {
|
||||
return fmt.Errorf("redis: ScanSlice(non-pointer %T)", container)
|
||||
}
|
||||
|
||||
// slice of the Ptr
|
||||
val = val.Elem()
|
||||
// if the container is slice
|
||||
if val.Kind() != reflect.Slice {
|
||||
return fmt.Errorf("redis: Wrong object type `%T` for ScanSlice(), need *[]*Type or *[]Type", container)
|
||||
}
|
||||
|
||||
for index, s := range sSlice {
|
||||
elem := internal.SliceNextElem(val)
|
||||
if err := Scan([]byte(s), elem.Addr().Interface()); err != nil {
|
||||
return fmt.Errorf("redis: ScanSlice failed at index of %d => %s, %s", index, s, err.Error())
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
Reference in New Issue
Block a user