Skip to content

Slice notation with negative indices #18662

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

Closed
lovasoa opened this issue Nov 5, 2014 · 4 comments
Closed

Slice notation with negative indices #18662

lovasoa opened this issue Nov 5, 2014 · 4 comments

Comments

@lovasoa
Copy link
Contributor

lovasoa commented Nov 5, 2014

fn main() {
    let a = "haha";
    println!("Nope. {}", a[1..-1]);
}

Compilation succeeds without any warning.
-1 is silently converted to an unsigned int, and I get an executable that panics with index 1 and/or 18446744073709551615 inhahado not lie on character boundary

I think there should be a compilation warning or error.

@thestinger
Copy link
Contributor

-1 is not silently converted to an unsigned integer. Rust's integer literals are generic and - is not included in the literal grammar. The 1 is inferred as a uint literal, and our unsigned integers provide an implementation of the - operator. Removing the - operator or warning when it's used with unsigned integers would need to go through the RFC process.

@thestinger
Copy link
Contributor

I don't think it's a great idea to have an - implementation for unsigned integers, but that isn't the existing consensus.

@lovasoa
Copy link
Contributor Author

lovasoa commented Nov 5, 2014

OK, I did not understand that.
But still, in this case, the compiler knows the size of the string. Couldn't we get a warning?

@xor2k
Copy link

xor2k commented Oct 28, 2022

I use this feature in Python a lot. The difference is: does one want to write the name of a variable a second time just to access it's tail? For short demos, it's okay, but for meaningful, not super-short variable names it gets annoying. Example: instead of

    let some_array_with_non_short_name = [1, 2, 3, 4, 5];

    let nice_slice = &some_array_with_non_short_name[1..some_array_with_non_short_name.len()-1];

one would have

    let some_array_with_non_short_name = [1, 2, 3, 4, 5];

    let nice_slice = &some_array_with_non_short_name[1..-1];

Is there something I'm missing out on? Can this be implemented without a great runtime impact?

lnicola added a commit to lnicola/rust that referenced this issue Dec 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants