gpt4 book ai didi

rust - 使用移动匹配变量的匹配语句引发编译器错误

转载 作者:行者123 更新时间:2023-12-03 11:34:43 25 4
gpt4 key购买 nike

我正在尝试遍历 Vec<String>文件路径并读取文件的内容。但是,match语句引发有关模式中变量的编译器错误。以下是代码:

    //paths: Vec<String>
//get counts in paths
for path in paths.iter() {
let mut path_result: Result<std::fs::File, std::io::Error>;
let file: std::fs::File;

if path != "-" {
path_result = std::fs::File::open(&path);
}

//match result with error
match path_result {
Ok(path_file) => { file = path_file },
Err(e) => {
match e.kind() {
std::io::ErrorKind::NotFound => { println!("{}: No such file or directory", &path) },
std::io::ErrorKind::PermissionDenied => { println!("{}: Permission denied", &path) },
_ => {
println!("{}: Unknown error", &path);
panic!("unknown error opening file");
}
}
continue;
}
};

/*get content from file variable*/
}
这是我收到的编译器错误:
error[E0382]: use of moved value
--> src/main.rs:60:16
|
51 | let mut path_result: Result<std::fs::File, std::io::Error>;
| --------------- move occurs because `path_result` has type `std::result::Result<File, std::io::Error>`, which does not implement the `Copy` trait
...
60 | Ok(path_file) => { file = path_file },
| ^^^^^^^^^ value used here after move
...
75 | }
| -
| |
| value moved here, in previous iteration of loop
| value moved here, in previous iteration of loop

error: aborting due to previous error; 16 warnings emitted

For more information about this error, try `rustc --explain E0382`.
error: could not compile `test`

To learn more, run the command again with --verbose.
警告与此代码段中未包含的未使用变量有关。
我试图借用 path_file 变量的内容,但收到相同的错误。我对这种情况的理解是,因为 path_file也不是 path_result稍后在 for 中使用 block 和 path_result在开始时重新绑定(bind),即使所有权超出 match 的范围,也应该没有问题陈述。然而,情况似乎并非如此。

最佳答案

你不能在 Rust 中使用未初始化的值。此代码不起作用:

// declare path_result here
let mut path_result: Result<std::fs::File, std::io::Error>;

// conditionally initialize it here
if path != "-" {
path_result = std::fs::File::open(&path);
}

// potentially use uninitialized value: error!
match path_result {
上面的代码也是您获得 value moved here, in previous iteration of the loop 的原因错误,因为您实际上并未初始化 path_result在循环的每次迭代中。一旦你重构代码以无条件初始化 path_result在每次迭代中,它都会编译:
fn example(paths: Vec<String>) {
for path in paths.iter() {
if path == "-" {
println!("skipping un-openable path: -");
continue;
}

let file = match std::fs::File::open(&path) {
Ok(path_file) => path_file,
Err(e) => {
match e.kind() {
std::io::ErrorKind::NotFound => {
println!("{}: No such file or directory", &path)
}
std::io::ErrorKind::PermissionDenied => {
println!("{}: Permission denied", &path)
}
_ => {
println!("{}: Unknown error", &path);
panic!("unknown error opening file");
}
}
continue;
}
};

/* get content from file variable */
}
}
playground

关于rust - 使用移动匹配变量的匹配语句引发编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65910494/

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