“借用时临时值下降” - 如何使用路径列表引用?

问题描述 投票:0回答:1

我想将列表(Vec 或数组)作为函数参数发送给(异步)函数。每个路径都用于生成一个线程,该线程对该文件执行一些操作。

这里的问题是,我无法找到正确的方法来使引用保持足够长的时间。我在函数参数中添加了“静态生命周期”,因为这在线程中起作用。但现在我在调用这个函数时无法获得满足这个要求的参考。

这是我的问题的一个小例子。原始代码要复杂得多。

use std::path::{Path, PathBuf};

fn main() {
    // Get paths from somewhere
    let paths = vec![
        PathBuf::from("/path/to/file.txt"),
        PathBuf::from("/path/to/file2.txt"),
    ];

    // Do multithreaded work with these paths
    do_something(&paths.iter().map(|path| path.as_path()).collect::<Vec<_>>());

    // Here some things regarding those files would happen.
}

fn do_something(paths: &'static [&Path]) {
    // Here paths is used again and required to use 'static lifetime
}
error[E0597]: `paths` does not live long enough
  --> src\main.rs:11:19
   |
5  |     let paths = vec![
   |         ----- binding `paths` declared here
...
11 |     do_something(&paths.iter().map(|path| path.as_path()).collect::<Vec<_>>());
   |                   ^^^^^                   -------------- returning this value requires that `paths` is borrowed for `'static`
   |                   |
   |                   borrowed value does not live long enough
12 | }
   | - `paths` dropped here while still borrowed

error[E0716]: temporary value dropped while borrowed
  --> src\main.rs:11:19
   |
11 |     do_something(&paths.iter().map(|path| path.as_path()).collect::<Vec<_>>());
   |     --------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-- temporary value is freed at the end of this statement
   |     |             |
   |     |             creates a temporary value which is freed while still in use
   |     argument requires that borrow lasts for `'static`
rust lifetime
1个回答
0
投票

在您的代码中,

&'static Path
指的是使用
collect
创建的时间对象,而不是上面的
vec!
,做这样的事情应该对您有用,
impl Iterator<Item = &'a Path>
对于不同类型是通用的可以像
Map<Iter<Cycle<..>>>

一样来
use std::path::{Path, PathBuf};

fn main() {
    // Get paths from somewhere
    let paths = vec![
        PathBuf::from("/path/to/file.txt"),
        PathBuf::from("/path/to/file2.txt"),
    ];

    // Do multithreaded work with these paths
    do_something(paths.iter().map(|path| path.as_path()));

    // Here some things regarding those files would happen.
}

fn do_something<'a>(paths: impl Iterator<Item = &'a Path>) {
    // Here paths is used again and required to use 'static lifetime
}
© www.soinside.com 2019 - 2024. All rights reserved.