gpt4 book ai didi

rust - 为什么当其中一个似乎超出范围时,带有字符串文字的代码会编译?

转载 作者:行者123 更新时间:2023-12-03 11:30:05 28 4
gpt4 key购买 nike

我遇到了section talking about lifetimes起初有点困惑。所以我决定通过编写一个小例子来尝试一下。 (Playground)

fn main() {
let b = "hello";
let mut d = "Unassigned";
{
let a = "hi";
let c = lifetime(&a, &b);
d = &c;
}

// My confusion happens here, I was expecting a compile-time error
// since the lifetime of 'c' is the same as 'a' which is in the previous block
// from my understanding. But this compiles just fine
println!("{}", d);
}

fn lifetime<'a, 'b>(test: &'a str, test2: &'b str) -> &'a str {
println!("{}, {}", test, test2);
return "returned value of lifetime";
}

据我了解, lifetime函数绑定(bind)生命周期 'a到返回的引用值。
所以通常我会期待这条线 println!("{}", d);在编译时因引用生命周期的错误而中断 'a超出范围,我错了。

我理解错了什么?
为什么要编译这段代码?

我看过 thisthat这基本上只是让我更加困惑,因为他们首先说出了我所期望的结果。

最佳答案

了解contravariance后正如上面评论中所指出的,我写了这个小片段(类似于问题)

struct Potato(i32);

fn doesnt_work() {
let b = Potato(1);
let d;
{
let a = Potato(2);
let c = lifetime2(&b, &a);
d = c;
}

// Compile-time error ! Borrowed value does not live long enough.
println!("{}", d.0);
}

fn lifetime2<'a, 'b>(test: &'a Potato, test2: &'b Potato) -> &'a Potato {
return &Potato(test.0);
}

现在给出了实际的预期编译时错误。

它在我原来的问题中发现生命周期被推断为 'static这是 str 的最高共同生命周期引用。

关于rust - 为什么当其中一个似乎超出范围时,带有字符串文字的代码会编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60822978/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com