← 中文资源

简体中文版本

语句临时值在分号处销毁

作为参数传入的临时值在语句结束的分号处销毁,let 绑定的值活到作用域结束;自定义 Drop 打印销毁时机,肉眼可见两种生命周期的差异。

阅读英文原文

实现要点

Lease 的 Drop impl 打印 dropped 加名字,把生命周期变得可见。accept(&Lease(“call argument”)) 展示临时值规则:值在分号处销毁,dropped call argument 先于 statement-ended 标记打印。

let 绑定活得更久:bound 存活到显式 drop(bound)——binding alive 先打印。内层块等价于作用域——inner block 在闭括号处销毁,先于 main ending 一行。

细节提醒

  • 实参位置的临时值随语句结束而销毁。
  • drop() 提前结束绑定,不必等作用域退出。

核心语句

accept(&Lease("call argument"));

代码示例

struct Lease(&'static str);

impl Drop for Lease {
    fn drop(&mut self) {
        println!("dropped {}", self.0);
    }
}

fn accept(lease: &Lease) {
    println!("borrowing {}", lease.0);
}

fn main() {
    // temporaries: the statement ends, the value dies at the semicolon
    accept(&Lease("call argument"));
    println!("-- statement ended --");

    // let-bound values live until the end of the scope (or drop())
    let bound = Lease("let bound");
    println!("-- binding alive --");
    drop(bound);

    // nested block: value drops when the block closes
    {
        let inner = Lease("inner block");
        println!("-- inner alive --");
    }
    println!("-- main ending --");
}