gpt4 book ai didi

rust - 我如何访问 Rust 目录中的文件?

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

我已经根据 Rust docs 编写了一个非常简单的脚本:

use std::fs::{self, DirEntry};
use std::path::Path;

fn main() {
let path = Path::new(".");
for entry in fs::read_dir(path)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
println!("directory found!");
}
}

}

但是我得到以下关于 ? 的编译错误:

error[E0277]: the trait bound `(): std::ops::Carrier` is not satisfied
--> test.rs:6:18
|
6 | for entry in fs::read_dir(path)? {
| -------------------
| |
| the trait `std::ops::Carrier` is not implemented for `()`
| in this macro invocation
|
= note: required by `std::ops::Carrier::from_error`

error[E0277]: the trait bound `(): std::ops::Carrier` is not satisfied
--> test.rs:7:21
|
7 | let entry = entry?;
| ------
| |
| the trait `std::ops::Carrier` is not implemented for `()`
| in this macro invocation
|
= note: required by `std::ops::Carrier::from_error`

我只部分理解 ? 但我知道要点是它允许您仅在 Ok 时对 Result 采取行动。这里的错误是它被用在 () 而不是 Result 上,这很奇怪。我尝试在没有 ? 的情况下实现循环:

use std::fs::{self, DirEntry};
use std::path::Path;

fn main() {
let path = Path::new(".");
for entry in fs::read_dir(path) {
println!("{}", entry.path());
}

}

但是我得到了错误:

error: no method named `path` found for type `std::fs::ReadDir` in the current scope
--> test.rs:7:30
|
7 | println!("{}", entry.path());
| ^^^^

这意味着 fs::read_dir 返回的 ReadDirDirEntry 项的迭代器,fs::read_dir 正在返回 (),它在某种程度上是 ReadDir 项的迭代器?

我很困惑。

可能值得一提的是我正在运行:rustc 1.16.0 (30cf806ef 2017-03-10)

最佳答案

第一个错误是because you cannot use try! or ? in a function returning () .

第二个错误是因为read_dir返回了一个Result:

pub fn read_dir<P: AsRef<Path>>(path: P) -> Result<ReadDir>

Result implements IntoIterator ,所以 path 实际上是您认为您拥有的迭代器。

Handling the errors并调用 Path::display 得到你想要的:

use std::fs;
use std::path::Path;

fn main() {
let path = Path::new(".");
for entry in fs::read_dir(path).expect("Unable to list") {
let entry = entry.expect("unable to get entry");
println!("{}", entry.path().display());
}
}

关于rust - 我如何访问 Rust 目录中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43395369/

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