rust - 如何对 Option<&Path> 进行模式匹配?
问题描述
我的代码看起来像这样:
// my_path is of type "PathBuf"
match my_path.parent() {
Some(Path::new(".")) => {
// Do something.
},
_ => {
// Do something else.
}
}
但我收到以下编译器错误:
expected tuple struct or tuple variant, found associated function `Path::new`
for more information, visit https://doc.rust-lang.org/book/ch18-00-patterns.html
我从 Rust 书中阅读了第 18 章,但我不知道如何使用Path
andPathBuf
类型修复我的特定场景。
如何通过检查特定值来匹配Option<&Path>
(根据文档,这是方法返回的) ?parent
Path::new("1")
解决方案
如果你想使用 a match
,那么你可以使用match guard。简而言之,你不能使用的原因Some(Path::new("."))
是因为Path::new(".")
不是模式。
match my_path.parent() {
Some(p) if p == Path::new(".") => {
// Do something.
}
_ => {
// Do something else.
}
}
但是,在这种特殊情况下,您也可以只使用这样的 if 表达式:
if my_path.parent() == Some(Path::new(".")) {
// Do something.
} else {
// Do something else.
}
推荐阅读
- php - mysqli每次只工作else条件而不是if条件
- c++ - c ++,析构函数会破坏类成员吗?
- c# - 在 Microsoft Bot Framework 中使用 Activity.text 进行路由
- android - 以编程方式将图像保存/转换为 webp 格式
- android - Android Lollipop Kiosk 模式应用程序更新问题
- swift - 尽管类名相同,但 xcode 中的 Ctrl 拖动不起作用
- mysql - 如何避免在节点mysql中插入重复记录?
- reactjs - 使用 ListView 搜索输入显示为空
- jenkins - 如何从 build.gradle 提取版本到 Jenkins 管道
- xamarin - Xamarin Forms iOS 应用程序无法通过 MDM 安装(但适用于免费预配)