29 ms·
Does Rust help solve overflow errors? Don't you need to explicitly used "saturated_add" or "checked_add"?
by thomasahle 4y ago
Does Rust help solve overflow errors? Don't you need to explicitly used "saturated_add" or "checked_add"?
- steveklabnik 4y agoRust doesn't directly solve overflow errors. What Rust does do is turn them into logic errors, rather than memory issues. To break it down: * Overflow with the default operators is not UB in Rust, it will either panic or two's compliment wrap, depending on various things (including things you can set to choose this global behavior). This already prevents various issues. * You can also explicitly choose to do various operations with whatever overflow semantics you want, as you mention with saturated_add and friends. * Because indexing is bounds checked, where in some languages an overflowed integer would lead to incorrect indexing and therefore possible memory problems, you'll either get a panic or a logic bug, not a memory bug. * If your integer isn't being used for indexing, you'll end up with some sort of error, but again, at worst a logical error, not a memory error.