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

标签 rust borrowing

我正在做这样的事情:

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/

相关文章:

rust - 有没有办法让 clap 覆盖 [ -h | --help ] 标记帮助文本?

debugging - 带 GDB 的 Rust 调试库

random - 生成随机数的最快方法

rust - 为什么允许我对迭代器的可变引用调用 take() ?

iterator - 具有内部可变性的 Vec

rust - 如何在将 debuginfo 添加到可执行文件时使 cargo 输入正确的 stdlib 源文件路径

rust - 有条件地迭代几个可能的迭代器之一

rust - 不可变值仍在移动

loops - 试图从 Rust 中的循环外部借用变量绑定(bind)

multidimensional-array - 有没有一种好方法可以在使用rust 的 ndarray 中进行重叠复制?