“Rust”的版本间的差异

来自wrc's Wiki
跳到导航 跳到搜索
 
第11行: 第11行:
 
// 或者
 
// 或者
 
*hmap.entry("key").or_insert(42) += 10;
 
*hmap.entry("key").or_insert(42) += 10;
 +
</syntaxhighlight>
 +
 +
== 代码片段 ==
 +
 +
=== 将某些不满足要求的 <code>Ok</code> 转化为 <code>Err</code> ===
 +
 +
<syntaxhighlight lang=rust>
 +
/// Turns into an `Err(anyhow::Error)` some `Ok`s that meet the predicate
 +
trait AdjustResult<T, E> {
 +
    fn adjust(self, predicate: impl Fn(&T) -> bool, msg: &str) -> Result<T>
 +
    where
 +
        E: Into<anyhow::Error>;
 +
}
 +
 +
impl<T, E> AdjustResult<T, E> for Result<T, E> {
 +
    fn adjust(self, predicate: impl Fn(&T) -> bool, msg: &str) -> Result<T>
 +
    where
 +
        E: Into<anyhow::Error>,
 +
    {
 +
        match self {
 +
            Ok(o) if predicate(&o) => Err(anyhow!(msg.to_string())),
 +
            Ok(o) => Ok(o),
 +
            Err(e) => Err(e.into()),
 +
        }
 +
    }
 +
}
 
</syntaxhighlight>
 
</syntaxhighlight>
  

2021年8月3日 (二) 21:18的最新版本

Rust 是一门赋予每个人构建可靠且高效软件能力的语言。

笔记

更新 HashMap 的值

直接使用 hmap["key"] = 42 会报错,说 HashMap 没有 implement IndexMut。可以使用如下的方法 [1]

*hmap.get_mut("key").unwrap() = 42;
// 或者
*hmap.entry("key").or_insert(42) += 10;

代码片段

将某些不满足要求的 Ok 转化为 Err

/// Turns into an `Err(anyhow::Error)` some `Ok`s that meet the predicate
trait AdjustResult<T, E> {
    fn adjust(self, predicate: impl Fn(&T) -> bool, msg: &str) -> Result<T>
    where
        E: Into<anyhow::Error>;
}

impl<T, E> AdjustResult<T, E> for Result<T, E> {
    fn adjust(self, predicate: impl Fn(&T) -> bool, msg: &str) -> Result<T>
    where
        E: Into<anyhow::Error>,
    {
        match self {
            Ok(o) if predicate(&o) => Err(anyhow!(msg.to_string())),
            Ok(o) => Ok(o),
            Err(e) => Err(e.into()),
        }
    }
}

参考资料