-
Notifications
You must be signed in to change notification settings - Fork 12.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
split_at family should return an Result #90410
Comments
Can you comment on the consistency of this pattern with the rest of the standard library API related to slices? |
Unsure I would said the std would prefer return an impl slice {
fn split_at_mid(&self, mid: usize) -> Option<(&[T], &[T])>;
fn split_at_mid_mut(&mut self, mid: usize) -> Option<(&mut [T], &mut [T])>;
}
impl str {
fn split_at_mid(&self, mid: usize) -> Option<(&str, &str)>;
fn split_at_mid_mut(&mut self, mid: usize) -> Option<(&mut str, &mut str)>;
} But return an Return a In short, this is consistent by returning a We could also consider having a structure in std for encapsulate the |
I would really like to have slice splitting methods that return an See my comment #111774 (comment) here about how the const version of the same thing only solved half my problem, and
I really don't think this API should return Results. It would be inconsistent with all other parts of |
Is it worth differentiating an out-of-bounds error from something like an invalid UTF code point in the case of strings? |
Why not that why I mention return a Result as a possibility, anyway that doesn't change much it would still be a programing error. |
I'd like to place another vote for fallible/non-panicking
If I could write this instead, it would eliminate three nested if levels and an impossible branch, while remaining verifiably panic-free. (Looks like the compiler can eliminate the panic if I write a regular split_at guarded by an is_char_boundary condition, but I don't like relying on the optimizer for that sort of thing.)
I wrote the code above assuming |
As of Rust 1.80.0, there is |
These function:
slice::split_at
slice::split_at_mut
str::split_at
str::split_at_mut
Are inconvenient to use, one need to check
len
(or be sure) then callsplit_at()
that will also checklen
, first this can lead to bad asm #74938 疠. Then it's inelegant. This would be ok if these function would be unsafe, so not checking the len twice.These function are better cause there return an
Option
:slice::split_first
slice::split_first_mut
slice::split_last
slice::split_last_mut
I propose we add the equivalent of
split_at
returning aResult
The
Err
bemid
orlen
(but we could imagine more precise error for example str could indicate char error boundary) or we keep it simple withOption
BTW: We miss
split_first()
andsplit_last()
onstr
.The text was updated successfully, but these errors were encountered: