首页 > 解决方案 > 使用 AsRef 时 String 所需的类型注释

问题描述

我正在像这样使用 Warp:


#[derive(Default)]
struct State {
    topics: HashMap<String, Topic>,
}

struct Topic {
    name: String,
    description: String,
    items: Vec<String>,
}

fn with_state(state: Arc<Mutex<State>>) -> impl Filter<Extract = (Arc<Mutex<State>>,), Error = std::convert::Infallible> + Clone {
    warp::any().map(move || state.clone())
}

#[tokio::main]
async fn main() {
    let state = Arc::new(Mutex::new(State::default()));

    let survey = warp::get()
        .and(warp::path!("survey" / String))
        .and(warp::path::end())
        .and(with_state(state.clone()))
        .and_then(|topic: String, state: Arc<Mutex<State>>| async move {
            let state = state.lock().unwrap();

            let topic = state.topics.get(&topic).ok_or(warp::reject::not_found())?;

            let res: Result<Value, Rejection> = Ok(json!({
                "name": topic.name,
                "items": topic.items.iter().map(AsRef::as_ref).collect::<Value>(),
            }));
            res
        })
    ...

如果我编译它会给出这个错误:

error[E0283]: type annotations needed for `std::string::String`
   --> src/main.rs:210:20
    |
210 |         .and_then(|topic: String, state: Arc<Mutex<State>>| async move {
    |                    ^^^^^ consider giving this closure parameter a type
    |
    = note: cannot resolve `std::string::String: std::convert::AsRef<_>`
    = note: required by `std::convert::AsRef::as_ref`

这真的很奇怪。这是什么意思consider giving this closure parameter a type?它不是已经有类型了吗?更奇怪的是,如果我注释掉这一行:

            "items": topic.items.iter().map(AsRef::as_ref).collect::<Value>(),

然后它编译!topic即使该行显然与参数无关。这是怎么回事?

标签: rustrust-warp

解决方案


啊,我刚刚发现它要我改变这个:

AsRef::as_ref

对此:

AsRef::<str>::as_ref

错误消息是完全错误的。


推荐阅读