Member-only story

50 Common Mistakes Rust Beginners Make: See How Many Have You Been Made?

Beck Moulton
8 min readMay 21, 2024

--

  1. Incorrect use of variable and immutable borrowing
let mut data = vec![1, 2, 3];
let x = &data[0];
data.push(4);
println!("{}", x);

Data cannot be modified when there are immutable references.

  1. Forgot Processing Options
fn main() {
let some_number = Some(5);
let sum = some_number + 5; // 错误:Option 类型不能这样直接使用
}

Use match or if let to handle options.

let sum = if let Some(n) = some_number { n + 5 } else { 0 };
  1. Expected reference instead of actual value
fn foo(x: &i32) {
// ...
}fn main() {
let x = 10;
foo(x); // 错误:应传递引用而不是值
}

Pass a reference instead of a value.

foo(&x);
  1. Mismatched type
fn main() {
let flag = true;
let number = if flag { 5 } else { "six" }; // 错误:不匹配的类型
}

Solution: Ensure that all branches return the same type.

let number = if flag { 5 } else { 6 };
  1. Forgot to import traits
use std::io::Write; // 因为 Write trait 已导入fn main() {
let mut buffer = Vec::new();
buffer.write_all(b"hello").unwrap();
// 现在可以正常使用 write_all 方法,因为 Write trait 已导入
}

You must import the Write trait to use its methods.

  1. Trying to modify it…

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet