Generics 编译器如何推断该框正在借用其内容借用的框?

Generics 编译器如何推断该框正在借用其内容借用的框?,generics,rust,reference,lifetime,ownership,Generics,Rust,Reference,Lifetime,Ownership,我认为它实际上是这样的: 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! pub struct Box<T, A = Global

我认为它实际上是这样的:

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!
pub struct Box<T, A = Global>(_, _)
    where A: AllocRef, T: ?Sized;

pub-struct-Box在本例中,生存期是包装在框中的类型
T
的一部分

&s
类型的
&a字符串
包装在框中,其中
'a
是编译器推断的引用的适当生存期。因此,
b
的类型是
Box PhantomData{
幻影数据
}
fn main(){
让s:String=String::from(“某些消息”);
让幻影=制作幻影(&s);
下降(s);;
让另一个幻影=幻影;
}
导致相同的错误,即从借用检查器的角度来看,
phantom
借用
s
,但实际上它没有引用
s


()

啊哈!然后,我在问题中的猜测是正确的!它会自动获取其泛型参数(即&“字符串”)的生存期,对吗?生成的类型
Box
有一个生存期参数,因为它包含一个引用。我不确定你所说的“它自动获得生存期…”是什么意思,更重要的是所有引用都有生存期——无论是显式的还是隐式的。我很困惑,对于所有的“结构”,s借用了T借用的东西。我想有某种counterexample@kwonryul我不这么认为。我在答案中添加了一个示例来说明这种行为不是特定于
Box
es的。
pub struct Box<'a, T, A = Global>(_, _)
    where A: AllocRef, T: ?Sized + 'a;
use std::marker::PhantomData;

fn make_phantom<T>(_: T) -> PhantomData<T> {
    PhantomData
}

fn main() {
    let s: String = String::from("some message");
    let phantom = make_phantom(&s);
    drop(s);
    let _another_phantom = phantom;
}