首页 > 解决方案 > as_deref 函数不会改变我的具体类型

问题描述

我想将我的转换Option<&String>Option<&str>withas_deref()但编译器似乎误解了我的意图。如果我用它替换它就.map(|e| e.as_str())可以了。

use std::collections::HashMap;

trait SipField {
    fn from(&self) -> Option<&str>;
}

impl SipField for HashMap<String, Vec<String>> {
    fn from(&self) -> Option<&str> {
        self.get("from")
            .or_else(|| self.get("f"))
            .and_then(|i| i.first())
            .as_deref()
    }
}
error[E0308]: mismatched types
  --> src/lib.rs:9:9
   |
9  | /         self.get("from")
10 | |             .or_else(|| self.get("f"))
11 | |             .and_then(|i| i.first())
12 | |             .as_deref()
   | |_______________________^ expected `str`, found struct `std::string::String`
   |
   = note: expected enum `std::option::Option<&str>`
              found enum `std::option::Option<&std::string::String>`

标签: rustoptional

解决方案


推荐阅读