Macros 尝试韩元';不能编译不匹配的类型
为什么这段代码不能编译Macros 尝试韩元';不能编译不匹配的类型,macros,rust,Macros,Rust,为什么这段代码不能编译 use std::fs; use std::io; use std::path::Path; fn do_job(path: &Path) -> io::Result<()> { let mut files: Vec<&Path> = Vec::new(); for entry in try!(fs::read_dir(path)) { entry = try!(entry); }
use std::fs;
use std::io;
use std::path::Path;
fn do_job(path: &Path) -> io::Result<()> {
let mut files: Vec<&Path> = Vec::new();
for entry in try!(fs::read_dir(path)) {
entry = try!(entry);
}
}
使用std::fs;
使用std::io;
使用std::path::path;
fn do_作业(路径:&path)->io::结果{
让mut文件:Vec=Vec::new();
用于try!(fs::read_dir(path))中的条目{
entry=try!(entry);
}
}
它与中的代码非常相似
编译错误:
<std macros>:3:43: 3:46 error: mismatched types:
expected `core::result::Result<std::fs::DirEntry, std::io::error::Error>`,
found `std::fs::DirEntry`
(expected enum `core::result::Result`,
found struct `std::fs::DirEntry`) [E0308]
<std macros>:3 $ crate:: result:: Result:: Ok ( val ) => val , $ crate:: result:: Result::
^~~
src/main.rs:13:17: 13:28 note: in this expansion of try! (defined in <std macros>)
<std macros>:3:43: 3:46 help: run `rustc --explain E0308` to see a detailed explanation
src/main.rs:12:5: 14:6 error: mismatched types:
expected `core::result::Result<(), std::io::error::Error>`,
found `()`
(expected enum `core::result::Result`,
found ()) [E0308]
src/main.rs:12 for entry in try!(fs::read_dir(path)) {
src/main.rs:13 entry = try!(entry);
src/main.rs:14 }
src/main.rs:12:5: 14:6 help: run `rustc --explain E0308` to see a detailed explanation
:3:43:3:46错误:不匹配的类型:
应为'core::result::result`,
找到'std::fs::DirEntry'`
(应为枚举'core::result::result`,
找到结构“std::fs::DirEntry`)[E0308]
:3$crate::result::result::Ok(val)=>val$crate::result::result::
^~~
src/main.rs:13:17:13:28注:在此扩展中,请尝试!(定义见)
:3:43:3:46帮助:运行'rustc--explain E0308'查看详细说明
src/main.rs:12:5:14:6错误:不匹配的类型:
应为'core::result::result`,
找到“()`
(应为枚举'core::result::result`,
已找到())[E0308]
src/main.rs:12用于输入try!(fs::read_dir(路径)){
src/main.rs:13 entry=try!(entry);
src/main.rs:14}
src/main.rs:12:5:14:6帮助:运行'rustc--explain E0308'查看详细说明
看起来您希望为循环中的每个目录项创建一个新绑定:
for entry in fs::read_dir(path)? {
let entry = entry?;
}
此新绑定将覆盖在for
表达式中引入的绑定
循环引入的条目
类型是结果
,您正试图使用?
(以前称为try!
)将其展开。但是,您试图将生成的DirEntry
分配给类型为Result
的绑定,因此会出现错误
第二个错误表示函数的返回值与声明的io::Result
类型不匹配。您只需返回Ok(())
:
fn do\u作业(路径:&path)->io::结果{
让mut文件:Vec=Vec::new();
对于fs::read_dir(路径)中的条目{
让进入=进入?;
//进程条目
}
好(())
}
@VictorAurélio-您缺少条目之前的let
。我添加了let
,但仍有错误(仅第二个错误)。@VictorAurélio-您需要从函数返回一个值,例如Ok(())
。
fn do_job(path: &Path) -> io::Result<()> {
let mut files: Vec<&Path> = Vec::new();
for entry in fs::read_dir(path)? {
let entry = entry?;
//process entry
}
Ok(())
}