生锈多生寿命结构可以访问超出寿命更长的参数
struct TwoStrRef<'a, 'b> {
str1: &'a str,
str2: &'b str,
}
fn main() {
let a_ref_struct;
let string_1 = String::from("hello");
let str_ref;
{
let string_2 = String::from("world");
a_ref_struct = TwoStrRef {
str1: &string_1,
str2: &string_2,
};
str_ref = a_ref_struct.str1;
}
// str_ref; // Ok
// a_ref_struct.str1; // Error: `string_2` does not live long enough borrowed value does not live long enough
}
struct twostrref
, a'和'b
有两个寿命参数,我分配了string_1
的参考String_2
(在不同的范围中,String_1
是一个较长的范围),str_1
和str_2
,以及当我尝试访问A_REF_STRUCT.STR1
String_2
之外(但是与String_1
)相同时,编译器将丢弃错误,这指示已指示。 String_2
寿命不够长。 str1
字段是否保存不在其范围之外的String_1
的引用?为什么如果我将STR1引用分配给str_ref
,我可以在同一范围内使用String_1
访问它?
struct TwoStrRef<'a, 'b> {
str1: &'a str,
str2: &'b str,
}
fn main() {
let a_ref_struct;
let string_1 = String::from("hello");
let str_ref;
{
let string_2 = String::from("world");
a_ref_struct = TwoStrRef {
str1: &string_1,
str2: &string_2,
};
str_ref = a_ref_struct.str1;
}
// str_ref; // Ok
// a_ref_struct.str1; // Error: `string_2` does not live long enough borrowed value does not live long enough
}
there are two lifetime parameters for struct TwoStrRef
, a'
and 'b
, and I assign the reference of string_1
and string_2
(which are in different scope and string_1
is the longer one) to field str_1
and str_2
, and when I try to access a_ref_struct.str1
outside the scope of string_2
(but the same with string_1
), the compiler will throw error, which indicated that string_2
does not live long enough. Isn't the str1
field holds the reference of string_1
that is not outside its scope ? And why if I assign the str1 reference to str_ref
, I can access it in the same scope with string_1
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
A_REF_STRUCT
在string_2
之前删除 脱离范围:这是必需的,因为否则任何访问其str2
field> field(例如,它可能在其滴剂处理程序中发生)是无效的。实际上,如果a_ref_struct
在删除string2
之后,其str2
将成为已发布的内存中的参考从未访问。在那里,您只是在
a_ref_struct.str1
(使用lifetime'a
ofstring_1
)中存储并存储该副本进入str_ref
。A_REF_STRUCT
可以(并且被)删除而不会影响(复制)参考。a_ref_struct
is dropped beforestring_2
goes out of scope: this is required because otherwise any access of itsstr2
field (which could potentially occur in its drop handler, for example) would be invalid. Indeed ifa_ref_struct
were to exist afterstring2
is dropped, itsstr2
would be a reference into released memory which is Undefined Behaviour even if that reference is never accessed.There you are just taking a copy of the reference that is held in
a_ref_struct.str1
(with lifetime'a
ofstring_1
) and storing that copy intostr_ref
.a_ref_struct
can then be (and is) dropped without affecting that (copied) reference.