提示:本网站现在为维护调试状态

Rust 所有権と借用:ライフタイム完全理解

Choyeon
Choyeon
2026年9月7日 1 分で読了 395 閲覧
399 字 2,184 文字 更新日 2026年11月8日
Rust 所有権と借用:ライフタイム完全理解
目次

Rust Ownership & Borrowing: Lifetimes Thoroughly Explained

Rust guarantees memory safety without a GC, powered by ownership and borrow checker. Validates legality at compile time with zero runtime cost but steepest learning curve.

Three Iron Ownership Rules

(1) Every value has exactly one owner. (2) When owner leaves scope value is dropped. (3) A value can have either one mutable reference OR any immutable references - never both at once. Most beginner lifetime errors violate #3.

use std::collections::HashMap;

#[derive(Debug, Clone)]
struct User { id: u32, username: String, profile: Option<Box<User>> }

struct UserCache<'a> {
    users: HashMap<u32, User>,
    last_accessed: Option<&'a User>,
}

impl<'a> UserCache<'a> {
    fn new() -> Self { Self { users: HashMap::new(), last_accessed: None } }
    fn insert(&mut self, user: User) { self.users.insert(user.id, user); }
    fn get(&'a mut self, id: u32) -> Option<&'a User> {
        if let Some(u) = self.users.get(&id) {
            self.last_accessed = Some(u);
            self.last_accessed
        } else { None }
    }
}

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

struct Parser<'s, 'b> where 's: 'b { source: &'s str, buffer: &'b mut [u8] }

impl<'s, 'b> Parser<'s, 'b> where 's: 'b {
    fn new(source: &'s str, buffer: &'b mut [u8]) -> Self { Self { source, buffer } }
}

fn main() {
    let s1 = String::from("hello");
    let s2 = s1.clone();
    println!("s1={s1}, s2={s2}");
    let a = String::from("short"); let b = String::from("longest string wins");
    println!("longest: {}", longest_str(&a, &b));
    let mut cache = UserCache::new();
    cache.insert(User { id: 1, username: "rosetta".into(), profile: None });
    let u = cache.get(1);
    println!("Got user: {:?}", u.map(|x| &x.username));
    let mut buf = vec![0u8; 1024];
    let p = Parser::new("input", buf.as_mut_slice());
    println!("Parser source len: {}", p.source.len());
}

Lifetime Annotations and Bounds

When functions/structs contain references, Rust needs explicit labels ('a, 'b) expressing validity relationships. Bound 's: 'b means lifetime 's outlives 'b - common in self-referential structs.

Common Error Root Cause Fix Pattern
use of moved value Ownership transferred already .clone() or borrow with &
cannot borrow X as mutable + immutable Borrow rule violated Narrow scopes / split blocks
missing lifetime specifier Compiler can't infer relation Add 'a tying inputs/outputs
lifetime may not live long enough Referenced value dropped earlier Extend scope / owning types

Best Practices

First versions use owning types everywhere (String/Vec/Box). After passing, convert parameters to references. Don't chase lifetime annotations prematurely - let compiler errors drive incremental fixes.

X微博Telegram

筆者について

投票

你最希望 Rosetta 优先加入哪项功能?

社区投票(演示数据,可后台删除)

コメント (4)

0 / 3000
运维老司机
运维老司机ops-notes.cn2026年9月14日

写得太好了,终于搞懂了分布式事务的几种方案区别,收藏了!

云端漫步
云端漫步cloud-notes.cloud2026年9月13日

补充一点:实际使用中如果遇到 MySQL 的 8 小时超时问题,可以在连接串里加 autoReconnect=true 参数,虽然官方不推荐但挺好用的。

考研加油鸭
考研加油鸭kaoyan-journey.xyz2026年9月12日

作为一个刚入行的后端新人,这篇文章帮我理清了好多概念,谢谢博主持续输出高质量内容!

画画的小鱼
画画的小鱼fishgallery.art2026年9月12日

好文!但是我觉得第三部分那个消息队列选型对比表有点偏向 Kafka 了,RocketMQ 在事务消息这块其实优势挺明显的。

関連記事

PostgreSQL クエリ最適化テクニック

PostgreSQL クエリ最適化テクニック

PostgreSQLクエリ最適化:EXPLAIN ANALYZEの読み方、インデックス種別選択、統計情報更新、結合戦略調整、パーティションテーブル設計。

1 分で読了
Linux 性能チューニング:perf + bpftrace + BCC

Linux 性能チューニング:perf + bpftrace + BCC

CPU/メモリ/IO/ネットワーク4次元:perfによるサンプリング、bpftraceワンライナー、BCC biolatency/offcputimeを用いた本番ボトルネック特定とトラブルシューティング。

1 分で読了
WebAssembly 入門:Rust → WASM + JS 呼び出し

WebAssembly 入門:Rust → WASM + JS 呼び出し

Rust→WASM開発環境構築:wasm-pack、wasm-bindgen型バインディング、JSからの呼び出し、メモリ共有による大規模データ処理。

1 分で読了
Zero Trust セキュリティアーキテクチャ入門:決して信用せず、常に検証

Zero Trust セキュリティアーキテクチャ入門:決して信用せず、常に検証

Zero Trust セキュリティモデル体系入門:「決して信用せず、常に検証」を原則に、伝統的 VPN=内部信頼の境界防衛思考を打ち砕く。身元認証(MFA/SAML)、端末健康チェック、最小権限RBAC、マイクロセグメンテーションmTLS、継続的信用スコア、可視化監査ログの6本柱を解説、実装ロードマップ付き。

1 分で読了
K8s Pod ライフサイクル + Init コンテナ + Sidecar

K8s Pod ライフサイクル + Init コンテナ + Sidecar

K8s Pod状態遷移Pending→Terminated、PostStart/PreStopフック、Init Container依存保証、Sidecarパターン、グレースフル停止ゼロダウンタイム設定。

1 分で読了
テストピラミッド:単体/結合/E2E 比率と実践

テストピラミッド:単体/結合/E2E 比率と実践

テストピラミッド体系解説:下層 単体テスト(多数・高速・Mock分離)、中層 結合テスト(実DB/メッセージ協調)、上層 E2E(少数・重要ユーザーフロー)。推奨比率 70/20/10、カバレッジ指標と実践ガイド。

1 分で読了