Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Like 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.



You still think in C limits of possibilities. Rust could just return Option as a result for [x] syntax.


And 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.)


There is HUGE difference between "unwrap" (which can found by grep) and mutual dangerous behavior. Programmer can only assume, not know, without additional checks. "Polluting with error" is much better than panicking.


And for safe iterations Rust has "for .. in".




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: