gpt4 book ai didi

rust - 借用时临时值(value)下降,但我不想租借

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

我正在做这样的事情:

fn main() {
//[1, 0, 0, 0, 99]; // return [2, 0, 0, 0, 99]
//[2, 3, 0, 3, 99]; // return [2,3,0,6,99]
//[2, 4, 4, 5, 99, 0]; // return [2,4,4,5,99,9801]
//[1, 1, 1, 4, 99, 5, 6, 0, 99]; // return [30,1,1,4,2,5,6,0,99]

let map: Vec<(&mut [usize], &[usize])> = vec![(&mut [1, 0, 0, 0, 99], &[2, 0, 0, 0, 99])];

for (x, y) in map {
execute_program(x);
assert_eq!(x, y);
}
}

pub fn execute_program(vec: &mut [usize]) {
//do something inside vec
}

Here the playground

问题是我不想在元组的第一个元素上使用let,我想借给execute_program:

error[E0716]: temporary value dropped while borrowed
--> src/main.rs:2:57
|
2 | let map: Vec<(&mut [usize], &[usize])> = vec![(&mut [1, 0, 0, 0, 99], &[2, 0, 0, 0, 99])];
| ^^^^^^^^^^^^^^^^ - temporary value is freed at the end of this statement
| |
| creates a temporary which is freed while still in use
3 |
4 | for (x, y) in map {
| --- borrow later used here
|
= note: consider using a `let` binding to create a longer lived value

但是我正在做的只是一个重构,因为我不想为我要测试的每个切片都做一个 let!

真的需要 let吗?

最佳答案

好吧,某些东西必须拥有这些数组中的每一个,因为引用不能拥有东西。而且数组的大小不同,因此所有者必须是一个指针。最常见的类似数组的拥有指针是Vec:

let map: Vec<(Vec<usize>, &[usize])> = vec![
(vec![1, 0, 0, 0, 99], &[2, 0, 0, 0, 99]),
(vec![2, 3, 0, 3, 99], &[2, 3, 0, 6, 99]),
(vec![2, 4, 4, 5, 99, 0], &[2, 4, 4, 5, 99, 9801]),
(vec![1, 1, 1, 4, 99, 5, 6, 0, 99], &[30, 1, 1, 4, 2, 5, 6, 0, 99]),
];

for (mut x, y) in map {
execute_program(&mut x);
assert_eq!(x, y);
}

因此,数组由 map拥有,并在必要时借用,如loganfsmyth在问题注释中也建议的那样。

您可能会担心进行不必要的分配的性能成本。这是使用单个 let的成本;由于数组的大小不尽相同,因此,如果要将它们放在堆栈上,实际上就没有办法用不同的 let声明它们。但是,您可以编写一个删除样板的宏。

等等,为什么它适用于 y

您可能想知道为什么我将 x转换为向量,却保留了 y的原样。答案是,因为 y是共享引用,所以这些数组都受 static promotion约束,因此 &[2, 0, 0, 0, 99]实际上是 &'static [usize; 5]类型,可以强制转换为 &'static [usize]&mut引用不会触发静态升级,因为在没有某种同步的情况下更改静态值是不安全的。

关于rust - 借用时临时值(value)下降,但我不想租借,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61957928/

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