gpt4 book ai didi

loops - 引用的生命周期比相同范围内的值短?

转载 作者:行者123 更新时间:2023-11-29 08:14:21 25 4
gpt4 key购买 nike

在我的代码中,一个值比对它的引用的生命周期更长,即使两者都是在相同的范围内创建的。我想知道原因以及如何调整引用的生命周期。

示例 1 被编译器接受...

let mut rxs: Vec<Receiver<String>> = Vec::new();
let mut txs: Vec<SyncSender<String>> = Vec::new();
for _ in 0..N {
let (tx, rx) = sync_channel(0);
txs.push(tx);
rxs.push(rx);
}

但示例 2 不是...

let sel = Select::new();
let mut handles: Vec<Handle<String>> = Vec::new();
let mut txs: Vec<SyncSender<String>> = Vec::new();
for _ in 0..N {
let (tx, rx) = sync_channel(0);
txs.push(tx);
handles.push(sel.handle(&rx));
}

编译器告诉我引用 &rxfor 循环的最后一行被借用,但是被丢弃for 循环的末尾,需要更长的生命周期,大概是因为引用被放置在生命周期更长的结构中。为什么引用的生命周期与值不同,如果值可以移动到第一个示例中的结构中,为什么不像第二个示例那样引用?

最后,我想知道为什么我没有在示例 3 中遇到同样的问题,即使引用被借用并传递到持续时间超过借...

let (txs, rxs): (Vec<SyncSender<String>>, Vec<Receiver<String>>) =
(0..N).map(|_| sync_channel(0)).unzip();
let handles: Vec<Handle<String>> =
rxs.iter().map(|x| sel.handle(&x)).collect();

最佳答案

在第一个示例中,您将 rx 移动到 rxs vec 中。这很好,因为您也移动了 rx 的所有权,它不会被删除。

在第二个示例中,您正在传递对 sel.handle() 的引用,这是表示它被借用的另一种方式。 rx 在每次循环迭代结束时被丢弃,但 handles 比整个循环都长。如果编译器没有阻止这种情况发生,那么 handles 将充满悬空指针。

But why would the reference have a different lifetime than the value

引用的生命周期总是比它引用的值短。必须是这种情况:引用必须存在并分配到内存,然后才能找到它的地址。删除一个值后,对它的任何引用都指向释放的内存,这些内存可以用于其他用途。

and if the value can be moved into a structure as in the first example, why not a reference like in the second?

在第二个例子中,引用正在被移动。但原始值不是。该引用现在指向以前由 rx 使用的空闲内存。

在第三个示例中,您创建了拥有所有 SenderReceiver 的向量。只要 txsrxs 在范围内,这些值就不会被删除。

关于loops - 引用的生命周期比相同范围内的值短?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43532275/

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