gpt4 book ai didi

macros - 尝试!不会编译不匹配的类型

转载 作者:行者123 更新时间:2023-11-29 08:34:53 26 4
gpt4 key购买 nike

为什么这个 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);
}
}

它与 docs 中的代码非常相似.

编译错误:

<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

最佳答案

看起来您想要为循环中的每个目录条目创建一个新绑定(bind):

for entry in fs::read_dir(path)? {
let entry = entry?;
}

这个新绑定(bind)将影响 for 中引入的那个表达。

entry 的类型循环引入的是Result<DirEntry>您正尝试使用 ? 解包(以前是 try! )。但是,您正试图分配结果 DirEntry到类型为 Result<DirEntry> 的绑定(bind),因此出现错误。

第二个错误表明您函数的返回值与 io::Result<()> 的声明类型不匹配.您可以简单地返回 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(())
}

关于macros - 尝试!不会编译不匹配的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36332802/

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