Convert a string value to a specified type, handling errors and optional default values.
(value string, converter func(string) (T, error), defaultValue ...T)
| 967 | |
| 968 | // Convert a string value to a specified type, handling errors and optional default values. |
| 969 | func Convert[T any](value string, converter func(string) (T, error), defaultValue ...T) (T, error) { |
| 970 | converted, err := converter(value) |
| 971 | if err != nil { |
| 972 | if len(defaultValue) > 0 { |
| 973 | return defaultValue[0], nil |
| 974 | } |
| 975 | |
| 976 | return converted, fmt.Errorf("failed to convert: %w", err) |
| 977 | } |
| 978 | |
| 979 | return converted, nil |
| 980 | } |
| 981 | |
| 982 | var ( |
| 983 | errParsedEmptyString = errors.New("parsed result is empty string") |