...
1 package funk
2
3 import (
4 "errors"
5 "fmt"
6 "reflect"
7 )
8
9
10 func Fill(in interface{}, fillValue interface{}) (interface{}, error) {
11 inValue := reflect.ValueOf(in)
12 inKind := inValue.Type().Kind()
13 if inKind != reflect.Slice && inKind != reflect.Array {
14 return nil, errors.New("Can only fill slices and arrays")
15 }
16
17 inType := reflect.TypeOf(in).Elem()
18 value := reflect.ValueOf(fillValue)
19 if inType != value.Type() {
20 return nil, fmt.Errorf(
21 "Cannot fill '%s' with '%s'", reflect.TypeOf(in), value.Type(),
22 )
23 }
24
25 length := inValue.Len()
26 newSlice := reflect.SliceOf(reflect.TypeOf(fillValue))
27 in = reflect.MakeSlice(newSlice, length, length).Interface()
28 inValue = reflect.ValueOf(in)
29
30 for i := 0; i < length; i++ {
31 inValue.Index(i).Set(value)
32 }
33 return in, nil
34 }
35
View as plain text