Rust Code Smells

Common code smells in Rust and how to fix them.


Unwrap/Expect Abuse

1// ❌ Bad
2let value = some_option.unwrap();
3let result = some_result.expect("failed");
4
5// βœ… Good
6let value = some_option.ok_or(Error::MissingValue)?;
7let result = some_result?;

Clone Instead of Borrow

 1// ❌ Bad
 2fn process(data: Vec<String>) {
 3    for item in data.clone() {
 4        println!("{}", item);
 5    }
 6}
 7
 8// βœ… Good
 9fn process(data: &[String]) {
10    for item in data {
11        println!("{}", item);
12    }
13}

Not Using Iterators

 1// ❌ Bad
 2let mut result = Vec::new();
 3for i in 0..items.len() {
 4    if items[i] > 10 {
 5        result.push(items[i] * 2);
 6    }
 7}
 8
 9// βœ… Good
10let result: Vec<_> = items.iter()
11    .filter(|&&x| x > 10)
12    .map(|&x| x * 2)
13    .collect();

Manual String Building

1// ❌ Bad
2let mut s = String::new();
3s.push_str("Hello");
4s.push_str(", ");
5s.push_str("world");
6
7// βœ… Good
8let s = format!("Hello, {}", "world");

Not Using Match

 1// ❌ Bad
 2if result.is_ok() {
 3    let value = result.unwrap();
 4    process(value);
 5} else {
 6    handle_error(result.unwrap_err());
 7}
 8
 9// βœ… Good
10match result {
11    Ok(value) => process(value),
12    Err(e) => handle_error(e),
13}

Related Snippets