Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rust 如何解决这个锈蚀寿命问题?_Rust - Fatal编程技术网

Rust 如何解决这个锈蚀寿命问题?

Rust 如何解决这个锈蚀寿命问题?,rust,Rust,我正在尝试并行读取目录中文件的内容。我遇到了人生的问题 我的代码如下所示: 使用std::io::fs; 使用std::io; 使用std::collections::HashMap; 使用std::comm; 使用std::io::File; fn main(){ let(tx,rx)=通信::信道();/(发送方,接收方) 让Path=fs::readdir(&Path::new(“资源/测试”).unwrap(); 对于paths.iter()中的路径{ 让任务_tx=tx.clone()

我正在尝试并行读取目录中文件的内容。我遇到了人生的问题

我的代码如下所示:

使用std::io::fs;
使用std::io;
使用std::collections::HashMap;
使用std::comm;
使用std::io::File;
fn main(){
let(tx,rx)=通信::信道();/(发送方,接收方)
让Path=fs::readdir(&Path::new(“资源/测试”).unwrap();
对于paths.iter()中的路径{
让任务_tx=tx.clone();
繁殖(proc(){
匹配文件::打开(路径)。读取\u到\u结束(){
确定(数据)=>task_tx.send((path.filename_str().unwrap(),data)),
Err(e)=>fail!(“无法读取其中一个文件!错误:{}”,e)
};
});
}
让mut results=HashMap::new();
对于范围内的u(0,paths.len()){
let(文件名,数据)=rx.recv();
结果。插入(文件名、数据);
}
println!(“{}”,结果);
}
我得到的编译错误是:

错误:
路径
的寿命不够长

注意:引用必须在静态生存期内有效

注:……但借用值仅对7:19的区块有效

我还尝试在循环中使用
进入iter()
(或之前的
移动iter()
),但没有多大成功


我怀疑这与生成的任务在整个
main()
范围之外保持活动状态有关,但我不知道如何解决这种情况。

错误消息可能有点混乱,但它告诉您的是,您试图在任务内部使用引用
路径。
因为spawn使用的是
proc
,所以只能使用可以将所有权转移到该任务的数据(
Send
kind)

要解决这个问题,您可以这样做(您可以使用move_iter,但不能访问循环后的路径):

第二个问题是您试图通过频道发送
&str
(文件名)。与用于任务的类型相同,使用的类型必须是
Send

    match File::open(&p).read_to_end() {
        Ok(data) => task_tx.send((p.filename_str().unwrap().to_string(), data)),
        Err(e) => fail!("Could not read one of the files! Error: {}", e)
    };

错误消息可能有点混乱,但它告诉您的是,您试图在任务内部使用引用
路径
。
因为spawn使用的是
proc
,所以只能使用可以将所有权转移到该任务的数据(
Send
kind)

要解决这个问题,您可以这样做(您可以使用move_iter,但不能访问循环后的路径):

第二个问题是您试图通过频道发送
&str
(文件名)。与用于任务的类型相同,使用的类型必须是
Send

    match File::open(&p).read_to_end() {
        Ok(data) => task_tx.send((p.filename_str().unwrap().to_string(), data)),
        Err(e) => fail!("Could not read one of the files! Error: {}", e)
    };