作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在做这样的事情:
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
}
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/
我是一名优秀的程序员,十分优秀!