我已经写了基于该Rust docs一个非常直接的脚本:如何访问Rust中的目录中的文件?
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
返回ReadDir
这是超过DirEntry
项目的迭代器,fs::read_dir
正在恢复()
这是不知怎的,迭代器通过ReadDir
项目?
我很困惑。
这也许值得一提的是,我快:rustc 1.16.0 (30cf806ef 2017-03-10)
你会发现这个没有在目录中访问的文件都做:在文档,代码不是内部'的main() '。 –