我想将列表(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`
在您的代码中,
&'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
}