rust-quiz:025-unit-infallible-match.rs
题目
use std::fmt::{self, Display};
struct S;
impl Display for S {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("1")
}
}
impl Drop for S {
fn drop(&mut self) {
print!("2");
}
}
fn f() -> S {
S
}
fn main() {
let S = f();
print!("{}", S);
}
关键
drop
当一个值失去全部引用的时候,生命就走到了终点,会调用drop
。
经常出现的有三种情况- 顶替:对一个变量重复赋值,老的值失去引用
move
:所有权进行转移,新生- 结束:脱离作用域
解题
能够想到的是,结果必然以为12
进行结尾。
主要分析一下let S = f()
。
fn f() -> S { S }
方法内部声明了一个S
,作为返回值,这里发生了move
。
因此会调用一次drop
,因此会打印1
。
答案
212
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: