maverick-rust-ownership

get2knowio 的头像作者 get2knowio

Rust ownership, borrowing, and lifetimes

📖 中文导读:Rust ownership, borrowing, and lifetimes 以下正文为该技能的原始 SKILL.md 内容(英文),上方安装命令可直接使用。

name: maverick-rust-ownership description: Rust ownership, borrowing, and lifetimes version: 1.0.0 triggers: - "&" - "&mut" - move - borrow - lifetime - "'a" - "'static" - clone() - Copy - Drop

Rust Ownership Skill

Ownership Rules

  1. Each value has exactly one owner
  2. When owner goes out of scope, value is dropped
  3. Values can be moved or borrowed

Borrowing Rules

  • One mutable reference OR any number of immutable references
  • References must always be valid
let s = String::from("hello");
let r1 = &s;      // OK
let r2 = &s;      // OK
let r3 = &mut s;  // ERROR: can't borrow as mutable

Lifetimes

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}

Review Severity

  • CRITICAL: Dangling references, use after move
  • MAJOR: Unnecessary clones, incorrect lifetime annotations
  • MINOR: Could use references instead of owned values