我正在做这样的事情:
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/