-
Notifications
You must be signed in to change notification settings - Fork 1.5k
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
Non-error slicing #3436
Comments
The use of |
Python's signed slicing can cause some real gotchas, like what do you think this returns for def endswith(a: str, b: str) -> bool:
return a[-len(b):] == b A better approach would be a special #[derive(Clone, Copy, ...)]
pub struct FromEnd(usize);
pub const END: FromEnd = FromEnd(0);
impl SliceIndex for FromEnd { .. };
impl Sub<usize> for FromEnd { .. };
// etc |
@FHTMitchell
Type inference seems to work: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=c067c8bf3600fc6c2e5f1c4411b7a4aa |
@SOF3 Ah good point. Such a conversion trait would probably break inference though :( How would the compiler know you want |
what about just using an enum with Start and End variants? there's no strict need to make it work with two different types together. |
In my experience, most of the time when These names are pretty much self-explaining, while the syntax proposed in the RFC could be very confusing. That If you want to remove items both from the start and the end of the slice, you could write |
Should this issue be named signed slicing instead of non-error slicing? |
Python's string slicing is so fabled for its error-prone, surprising behavior that university professors, in my experience, use it as prime example of a poorly-designed API. A feature like this one is best experimented with by publishing a public crate. @FHTMitchell posted an example of how this might work without changes to the standard library. |
In Python and JavaScript, there's a function vec.slice that never throws an error:
means "remove the first
x
elements from the start and the first y elements from the end". Rust currently throws an error ifx
is greater thanvec.len() - 1
. It returns an empty vec when the span includes no elements: that's what you want for many use cases.It's convenient to do Python/JavaScript like accesses as an idiomatic version of
take
ing anddrop
ing (in the Haskell sense) in Rust.For clarity, here is an example implementation:
The text was updated successfully, but these errors were encountered: