gpt4 book ai didi

rust - 从 walkdir 的文档中实现代码

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

我是 Rust 的新手,并试图弄清楚我在这里做错了什么。来自 docs.rs page on walkdir :

The following code recursively iterates over the directory given and prints the path for each entry:

use walkdir::WalkDir;

for entry in WalkDir::new("foo") {
println!("{}", entry?.path().display());
}

但是,当我尝试将它作为一个简单的程序运行时:
use walkdir::WalkDir;
fn main() {
for entry in WalkDir::new("~/Documents/ExampleDir/") {
println!("{}", entry?.path().display());
}
}
我收到编译错误:
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `Try`)
--> src/main.rs:4:24
|
2 | / fn main() {
3 | | for entry in WalkDir::new("foo") {
4 | | println!("{}", entry?.path().display());
| | ^^^^^^ cannot use the `?` operator in a function that returns `()`
5 | | }
6 | | }
| |_- this function should return `Result` or `Option` to accept `?`
|
= help: the trait `Try` is not implemented for `()`
= note: required by `from_error`
如果我删除 ?运算符然后我得到一个不同的编译错误:
error[E0599]: no method named `path` found for enum `std::result::Result<walkdir::DirEntry, walkdir::Error>` in the current scope
--> src/main.rs:4:30
|
4 | println!("{}", entry.path().display());
| ^^^^ method not found in `std::result::Result<walkdir::DirEntry, walkdir::Error>`
我在这里做错了什么?这是我的代码或文档中的问题吗?

最佳答案

?是 match 语句的简写。见 The question mark operator .

The question mark operator (?) unwraps valid values or returns erroneous values, propagating them to the calling function. It is a unary postfix operator that can only be applied to the types Result<T, E> and Option.


( main ) 函数需要类型为 Result 的返回值:
use std::error::Error;
use walkdir::WalkDir;

fn main() -> Result<(), Box<dyn Error>> {
for entry in WalkDir::new("~/Documents/ExampleDir/") {
println!("{}", entry?.path().display());
}
Ok(())
}

关于rust - 从 walkdir 的文档中实现代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66463853/

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