4 ms·
Then use the get() function on an array/slice. It returns an Option so it won't perform an access off the end of the array, and you can catch it.
by moosingin3space 10y ago
Then use the get() function on an array/slice. It returns an Option so it won't perform an access off the end of the array, and you can catch it.
- EugeneOZ 10y agothanks, I do. Only thing left is explain it to everybody else to avoid panicking in 3-party crates. I really hate when people use panicking just because it's easier than error handling. So it was "surprise" to see such behavior from "[x]" construction.
- cesarb 10y agoLike in C, you are not supposed to pass out-of-bounds indexes to the [] operator. If anyone does so, it's a bug. Rust converts it to a panic, which safely terminates the thread/program, instead of C's undefined behavior. You can also catch this panic at the thread boundary, so other threads in your program can keep running, unless the program was compiled to call abort() on panic.
- EugeneOZ 10y agoYou still think in C limits of possibilities. Rust could just return Option as a result for [x] syntax.
- cesarb 10y agoAnd then people would simply call .unwrap() on the return of the [] operator, leading to the same situation. It's extremely common for an array dereference to always be within the bounds, by code construction (I'm iterating over the indexes of the array, or I have an index into the array saved inside some other structure, and so on). The programmer knows it will never be out of bounds. The assert!() within the [] operator is only to protect you when the programmer gets it wrong, and in a correctly written program, will never trigger. (The alternative instead of .unwrap() would be to propagate the error, polluting the whole program with code to handle errors which never will happen. And since they will never happen, many programmers would simply start ignoring them - and in the process, they would by accident end up ignoring errors that can happen. Not a good situation.)