Slice ending bounds past the end of the slicee

It would be cool if:

let s = b"hello";
let slc = &s[..100];

worked, and returned a slice of min(s.len(), 100) instead of panicing. This is the behavior I expected coming from Python. :smile: This is useful for ensuring input is no larger than a certain size.

I’d find that behavior surprising. Also, couldn’t you just write &s[..min(s.len(), 100)], which would be much clearer that nothing magical is going on, and show what exactly you hope the code will do.

2 Likes

Rust likes ergonomics, but not at the cost of magicking away some internal details. Rust tends to be more explicit in these situations.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.