#iterator #map

map-ok

迭代器中 Ok 变体的映射

2 个版本 (1 个稳定版本)

1.0.0 2024年3月8日
0.1.0 2023年12月11日

#492 in 开发工具


用于 globescraper

MIT 许可证

13KB
166

MapOk / BoxOk

此 crate 提供了 MapOk trait,允许将迭代器中的 Ok 变体映射到不同类型。您不必在 map 调用中匹配 Result 变体,只需调用

fn example() {
    let input = ["10", "20", "x", "30"];
    let mut iterator = input.into_iter().map(u32::from_str).map_ok(|x| x * 100);
}

代替更冗长的

fn example() {
    let input = ["10", "20", "x", "30"];
    let mut iterator = input.into_iter().map(u32::from_str).map(|x| match x {
        Ok(x) => Ok(x * 100),
        Err(e) => Err(e),
    });
}

同样,box_ok 函数将 Ok 变体的内容包装到 Box 中,即它表现得像 .map_ok(Box::new)

fn example() {
    let input = ["10", "20", "x", "30"];
    let results: Vec<Result<Box<u32>, ParseIntError>> = input
        .into_iter()
        .map(u32::from_str)
        .map_ok(|x| x * 100)
        .box_ok()
        .collect();
}

示例

以下是一个包含更复杂解析的工作示例

use std::num::ParseIntError;
use std::str::FromStr;
use map_ok::MapOk;

/// A struct that represents a person.
struct Person {
    age: u8,
}

impl Person {
    /// Constructs a new `Person` instance.
    ///
    /// # Arguments
    ///
    /// * `age` - an unsigned 8-bit integer representing a person's age.
    fn new(age: u8) -> Self {
        Person { age }
    }
}

impl FromStr for Person {
    type Err = ParseIntError;

    /// Converts a string slice into a `Person` instance.
    ///
    /// # Arguments
    ///
    /// * `s` - a string slice that holds the person's age.
    ///
    /// # Returns
    ///
    /// A result that is either a `Person` or a `ParseIntError`.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let age = u8::from_str(s)?;
        Ok(Person::new(age))
    }
}

/// In this example, the `map_ok` function is utilized to transform the `Ok` variant of a `Result`
/// by mapping the value of the `Person` age.
fn example() {
    let input = vec!["10", "20", "x", "30"];
    let mut iterator = input.into_iter()
        .map(Person::from_str)
        .map_ok(|p| p.age);

    assert_eq!(iterator.next(), Some(Ok(10)));
    assert_eq!(iterator.next(), Some(Ok(20)));
    assert!(iterator.next().unwrap().is_err());
    assert_eq!(iterator.next(), Some(Ok(30)));
    assert_eq!(iterator.next(), None);
}

无运行时依赖