3 个版本
| 0.1.3 | 2021 年 8 月 15 日 |
|---|---|
| 0.1.2 | 2021 年 1 月 16 日 |
| 0.1.1 | 2020 年 1 月 26 日 |
在 Rust 模式 中排名第 2542
每月下载量 493
在 4 个 crate 中使用
10KB
78 行
ref-map
Rust crate,提供对 Option<T> 和 Result<T, E> 的便利特质。
没有依赖项,应在任何 Rust 发布渠道上工作。
提供了三种方法,ref_map() 用于 Some(_) 和 Ok(_),以及 ref_map_err() 用于 Err(_)。这允许轻松地从可能值映射借用值。
use ref_map::*;
let string: Option<String> = Some("hello world\n".into());
// Without ref-map:
// the .as_ref() is necessary because otherwise it tries to consume the String
let message: Option<&str> = string.as_ref().map(|s| s.trim());
// With ref-map:
let message: Option<&str> = string.ref_map(|s| s.trim());
还提供了 ref_map() 用于 Result<T, E> 的 Ok,以及 ref_map_err() 用于 Err。
版权 (C) 2020-2021 Ammon Smith
在 MIT 许可证下提供。
lib.rs:
它引入了两个特质,OptionRefMap 和 ResultRefMap,它们分别向它们各自的标准库枚举添加方法,以避免在它们的值上执行任何 .map() 方法之前需要添加 .as_ref()。
这在您想从 Option 或 Result 中借用,但又想避免先获取内部值引用的模板代码时非常有用。
use ref_map::*;
let string: Option<String> = Some("hello world\n".into());
// Without ref-map:
// the .as_ref() is necessary because otherwise it tries to consume the String
let message: Option<&str> = string.as_ref().map(|s| s.trim());
// With ref-map:
let message: Option<&str> = string.ref_map(|s| s.trim());
同样,对于 Result,有 .ref_map() 和 .ref_map_err() 方法,可以模仿它们的 .map() 和 .map_err() 方法
let answer: Result<PathBuf, String> = Ok(PathBuf::from("/test"));
// Mapping borrowed Ok(_) to another type
let path: Result<&Path, &String> = answer.ref_map(|p| p.as_path());
// Mapping borrower Err(_)
let error: Result<&PathBuf, &str> = answer.ref_map_err(|e| e.as_str());