为什么这辈子不"expire"?
Why does this lifetime not "expire"?
对于下面的区块,生命周期'b
和'c
什么时候结束?
use core::ops::Deref;
#[derive(Debug)]
struct A<'b, 'c, T> {
child_b: &'b T,
child_c: &'c T
}
impl<'b, 'c, T> A<'b, 'c, T> {
pub fn new_wrapper(b_value: &'b T, c_value: &'c T) -> A<'b, 'c, T> {
A {
child_b: b_value,
child_c: c_value
}
}
}
fn doesnt_drop_borrow<T: Copy>(ty: &T) {
*ty;
}
fn drop<T>(ty: T) { }
fn main() {
let b: String = "wonderful".into();
let c: String = "lifetime".into();
let a = A::new_wrapper(&b, &c);
println!("hello this {:?} world", &a);
doesnt_drop_borrow(&a.child_c);
drop(a.child_c);
println!("hello this {:?} world", &a);
}
由于 a.child_c
的类型为 &String
,因此 ty
中的参数
doesnt_drop_borrow(&a.child_c)
的类型为 &&String
,并且
*ty
有类型 &String
所以原来的 String
(c
) 不会
被丢弃。
我不知道是什么激发了你的问题,但我想
事实上,在调用 drop(a.child_c)
之后,您仍然可以使用 a
。
此函数的名称具有误导性,因为此处的 ty
参数
具有类型 &String
(与 a.child_c
相同)。
所以 ty
参数显示为原始的新的不可变借用
c
, then 立即被丢弃,但原来的 c
并没有被丢弃。
当引用被删除时,引用的值不是。
None这两个函数实际上移动了原来的String
,
他们只处理引用。
所以 b
和 c
一直活到 main()
结束,a
也是如此
其中包含对它们的引用。
对于下面的区块,生命周期'b
和'c
什么时候结束?
use core::ops::Deref;
#[derive(Debug)]
struct A<'b, 'c, T> {
child_b: &'b T,
child_c: &'c T
}
impl<'b, 'c, T> A<'b, 'c, T> {
pub fn new_wrapper(b_value: &'b T, c_value: &'c T) -> A<'b, 'c, T> {
A {
child_b: b_value,
child_c: c_value
}
}
}
fn doesnt_drop_borrow<T: Copy>(ty: &T) {
*ty;
}
fn drop<T>(ty: T) { }
fn main() {
let b: String = "wonderful".into();
let c: String = "lifetime".into();
let a = A::new_wrapper(&b, &c);
println!("hello this {:?} world", &a);
doesnt_drop_borrow(&a.child_c);
drop(a.child_c);
println!("hello this {:?} world", &a);
}
由于 a.child_c
的类型为 &String
,因此 ty
中的参数
doesnt_drop_borrow(&a.child_c)
的类型为 &&String
,并且
*ty
有类型 &String
所以原来的 String
(c
) 不会
被丢弃。
我不知道是什么激发了你的问题,但我想
事实上,在调用 drop(a.child_c)
之后,您仍然可以使用 a
。
此函数的名称具有误导性,因为此处的 ty
参数
具有类型 &String
(与 a.child_c
相同)。
所以 ty
参数显示为原始的新的不可变借用
c
, then 立即被丢弃,但原来的 c
并没有被丢弃。
当引用被删除时,引用的值不是。
None这两个函数实际上移动了原来的String
,
他们只处理引用。
所以 b
和 c
一直活到 main()
结束,a
也是如此
其中包含对它们的引用。