Pitfalls of Safe Rust

https://news.ycombinator.com/rss Hits: 11
Summary

When people say Rust is a “safe language”, they often mean memory safety. And while memory safety is a great start, it’s far from all it takes to build robust applications. Memory safety is important but not sufficient for overall reliability. In this article, I want to show you a few common gotchas in safe Rust that the compiler doesn’t detect and how to avoid them. Even in safe Rust code, you still need to handle various risks and edge cases. You need to address aspects like input validation and making sure that your business logic is correct. Here are just a few categories of bugs that Rust doesn’t protect you from: Type casting mistakes (e.g. overflows) Logic bugs Panics because of using unwrap or expect Malicious or incorrect build.rs scripts in third-party crates Incorrect unsafe code in third-party libraries Race conditions Let’s look at ways to avoid some of the more common problems. The tips are roughly ordered by how likely you are to encounter them. Click here to expand the table of contents. Overflow errors can happen pretty easily: fn calculate_total(price: u32, quantity: u32) -> u32 { price * quantity } If price and quantity are large enough, the result will overflow. Rust will panic in debug mode, but in release mode, it will silently wrap around. To avoid this, use checked arithmetic operations: fn calculate_total(price: u32, quantity: u32) -> Result<u32, ArithmeticError> { price.checked_mul(quantity) .ok_or(ArithmeticError::Overflow) } Static checks are not removed since they don’t affect the performance of generated code. So if the compiler is able to detect the problem at compile time, it will do so: fn main() { let x: u8 = 2; let y: u8 = 128; let z = x * y; } The error message will be: error: this arithmetic operation will overflow --> src/main.rs:4:13 | 4 | let z = x * y; | ^^^^^ attempt to compute `2_u8 * 128_u8`, which would overflow | = note: `#[deny(arithmetic_overflow)]` on by default For all other cases, use checked_add, checked_sub, check...

First seen: 2025-04-06 18:15

Last seen: 2025-04-07 04:16