【发布时间】:2021-01-05 10:30:23
【问题描述】:
let s: String = String::from("some message");
let b: Box<&String> = Box::<&String>::new(&s);
drop(s);
let another_box = b; // error! b (which borrows s) is used later!
所以,上面的代码看起来很简单。
b 显然是在借用人类意义上的 s。
但是,我认为这很神奇: 没有任何生命周期语句,编译器怎么知道呢?
根据 Rust 的标准库,
Box的声明如下:
pub struct Box<T, A = Global>(_, _)
where A: AllocRef, T: ?Sized;
而我认为它的真正含义如下:
pub struct Box<'a, T, A = Global>(_, _)
where A: AllocRef, T: ?Sized + 'a;
我认为在结构具有通用参数类型的所有情况下,生命周期(或借用)不会自动移动。 还是这样??
【问题讨论】:
标签: generics rust reference lifetime ownership