gpt4 book ai didi

rust - 如何解决这个 Rust 生命周期问题?

转载 作者:行者123 更新时间:2023-11-29 08:13:04 25 4
gpt4 key购买 nike

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

我的代码是这样的:

use std::io::fs;
use std::io;
use std::collections::HashMap;
use std::comm;
use std::io::File;

fn main() {
let (tx, rx) = comm::channel(); // (Sender, Receiver)

let paths = fs::readdir(&Path::new("resources/tests")).unwrap();

for path in paths.iter() {
let task_tx = tx.clone();

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

let mut results = HashMap::new();

for _ in range(0, paths.len()) {
let (filename, data) = rx.recv();

results.insert(filename, data);
}

println!("{}", results);
}

我得到的编译错误是:

error: paths does not live long enough

note: reference must be valid for the static lifetime...

note: ...but borrowed value is only valid for the block at 7:19

我还尝试在循环中使用 into_iter()(或之前的 move_iter()),但没有成功。

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

最佳答案

错误消息可能有点令人困惑,但它告诉您的是您正在尝试在任务中使用引用 path。因为 spawn 使用 proc,所以您只能使用可以将所有权转移给该任务的数据(Send 类型)。

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

for path in paths.iter() {
let task_tx = tx.clone();

let p = path.clone();
spawn(proc() {
match File::open(&p).read_to_end() {

第二个问题是您试图通过 channel 发送 &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)
};

关于rust - 如何解决这个 Rust 生命周期问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25941815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com