cast.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package slices
  2. import (
  3. "reflect"
  4. "github.com/bradfitz/iter"
  5. )
  6. // Returns a copy of all the elements of slice []T as a slice of interface{}.
  7. func ToEmptyInterface(slice interface{}) (ret []interface{}) {
  8. v := reflect.ValueOf(slice)
  9. l := v.Len()
  10. ret = make([]interface{}, 0, l)
  11. for i := range iter.N(v.Len()) {
  12. ret = append(ret, v.Index(i).Interface())
  13. }
  14. return
  15. }
  16. // Makes and sets a slice at *ptrTo, and type asserts all the elements from
  17. // from to it.
  18. func MakeInto(ptrTo interface{}, from interface{}) {
  19. fromSliceValue := reflect.ValueOf(from)
  20. fromLen := fromSliceValue.Len()
  21. if fromLen == 0 {
  22. return
  23. }
  24. // Deref the pointer to slice.
  25. slicePtrValue := reflect.ValueOf(ptrTo)
  26. if slicePtrValue.Kind() != reflect.Ptr {
  27. panic("destination is not a pointer")
  28. }
  29. destSliceValue := slicePtrValue.Elem()
  30. // The type of the elements of the destination slice.
  31. destSliceElemType := destSliceValue.Type().Elem()
  32. destSliceValue.Set(reflect.MakeSlice(destSliceValue.Type(), fromLen, fromLen))
  33. for i := range iter.N(fromSliceValue.Len()) {
  34. // The value inside the interface in the slice element.
  35. itemValue := fromSliceValue.Index(i)
  36. if itemValue.Kind() == reflect.Interface {
  37. itemValue = itemValue.Elem()
  38. }
  39. convertedItem := itemValue.Convert(destSliceElemType)
  40. destSliceValue.Index(i).Set(convertedItem)
  41. }
  42. }