3 ms·
> You obviously can, but indexing with `[]` is the default way one would think of doing and it can certainly be surprising that it panics. True. I think it wou
by HKH2 4y ago
> You obviously can, but indexing with `[]` is the default way one would think of doing and it can certainly be surprising that it panics.
True. I think it would've been nicer to make it return an Option type, but I guess performance would suffer if they made everything consistent.
- junon 4y agoIt's opt in, like most things in rust. Any time you have an option, you can simply unwrap it to say "I'm asserting I know this is a 'some' value, and if it's perhaps not, then please panic". Forcing an unwrap in every single case would indeed kill performance.
- Arnavion 4y agoNo. There would be no difference in performance if it returned an Option and required the caller to unwrap. That's what `[]` is doing internally anyway. As are all the other functions I linked that are documented as panicking - they're doing tests manually and `panic!()`'ing if those tests fail anyway. As I said in the original comment, the reason these functions panic is that the common case for them is where the caller is using parameters that ought to be valid already (either hard-coded or already checked). So it would be less ergonomic to require the callers to handle an error that they know won't happen.
- junon 4y agoIf the compiler wasn't able to make optimizations then you're right. But it can, especially when it can determine the bounds checks are unnecessary.
- Arnavion 4y agoAnd those optimizations apply regardless of whether the function checks the parameter internally and panics on failure, or if you check the parameter before calling the function and unwrap the function result. Again, there is no difference. There's really no need to argue about this. Feel free to godbolt it.
- junon 4y agoYou're right. https://godbolt.org/z/cfr8MEG6j https://godbolt.org/z/cfr8MEG6j https://godbolt.org/z/7crr4n66Y https://godbolt.org/z/7crr4n66Y I suppose I'm used to C/C++ compilers not going as far down the optimization rabbit hole as Rust seems to, where they often miss more complex optimizations like this in sufficiently advanced wrapper types etc.