-
Notifications
You must be signed in to change notification settings - Fork 273
/
fill.go
34 lines (29 loc) · 816 Bytes
/
fill.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package funk
import (
"errors"
"fmt"
"reflect"
)
// Fill fills elements of array with value
func Fill(in interface{}, fillValue interface{}) (interface{}, error) {
inValue := reflect.ValueOf(in)
inKind := inValue.Type().Kind()
if inKind != reflect.Slice && inKind != reflect.Array {
return nil, errors.New("can only fill slices and arrays")
}
inType := reflect.TypeOf(in).Elem()
value := reflect.ValueOf(fillValue)
if inType != value.Type() {
return nil, fmt.Errorf(
"cannot fill '%s' with '%s'", reflect.TypeOf(in), value.Type(),
)
}
length := inValue.Len()
newSlice := reflect.SliceOf(reflect.TypeOf(fillValue))
in = reflect.MakeSlice(newSlice, length, length).Interface()
inValue = reflect.ValueOf(in)
for i := 0; i < length; i++ {
inValue.Index(i).Set(value)
}
return in, nil
}