ConvertSlice converts a source slice to a destination slice. - Elements are converted one by one using the Convert function. - Validation is performed on each element if checkValidateTag is true. - The destination slice is initialized with the source length. - On error, the destination slice is tru
(src reflect.Value, dst reflect.Value, checkValidateTag bool)
| 486 | // - On error, the destination slice is truncated to the number of |
| 487 | // successfully converted elements. |
| 488 | func ConvertSlice(src reflect.Value, dst reflect.Value, checkValidateTag bool) error { |
| 489 | if dst.Kind() == reflect.Pointer { |
| 490 | if dst.IsNil() && !dst.CanSet() { |
| 491 | return fmt.Errorf("convert: dst is %w", ErrNilValue) |
| 492 | } |
| 493 | initPtr(dst) |
| 494 | dst = dst.Elem() |
| 495 | } |
| 496 | |
| 497 | if !dst.CanSet() { |
| 498 | return fmt.Errorf("convert: dst is %w", ErrUnsettable) |
| 499 | } |
| 500 | |
| 501 | if src.Kind() != reflect.Slice { |
| 502 | return Convert(src, dst, checkValidateTag) |
| 503 | } |
| 504 | |
| 505 | srcLen := src.Len() |
| 506 | if srcLen == 0 { |
| 507 | dst.SetZero() |
| 508 | return nil |
| 509 | } |
| 510 | if dst.Kind() != reflect.Slice { |
| 511 | return fmt.Errorf("convert: %w for %s to %s", ErrUnsupportedConversion, dst.Type(), src.Type()) |
| 512 | } |
| 513 | |
| 514 | var sliceErrs gperr.Builder |
| 515 | numValid := 0 |
| 516 | gi.ReflectInitSlice(dst, srcLen, srcLen) |
| 517 | for j := range srcLen { |
| 518 | err := Convert(src.Index(j), dst.Index(numValid), checkValidateTag) |
| 519 | if err != nil { |
| 520 | sliceErrs.AddSubjectf(err, "[%d]", j) |
| 521 | continue |
| 522 | } |
| 523 | numValid++ |
| 524 | } |
| 525 | |
| 526 | if dst.Type().Implements(reflect.TypeFor[CustomValidator]()) { |
| 527 | err := dst.Interface().(CustomValidator).Validate() |
| 528 | if err != nil { |
| 529 | sliceErrs.Add(err) |
| 530 | } |
| 531 | } |
| 532 | |
| 533 | if err := sliceErrs.Error(); err != nil { |
| 534 | dst.SetLen(numValid) // shrink to number of elements that were successfully converted |
| 535 | return err |
| 536 | } |
| 537 | return nil |
| 538 | } |
| 539 | |
| 540 | // ConvertString converts a string value to the destination reflect.Value. |
| 541 | // - It handles various types including numeric types, booleans, time.Duration, |