【问题标题】:Type annotations needed for String when using AsRef使用 AsRef 时 String 所需的类型注释
【发布时间】:2020-05-31 19:30:26
【问题描述】:

我正在像这样使用 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 参数无关。怎么回事?

【问题讨论】:

    标签: rust rust-warp


    【解决方案1】:

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

    AsRef::as_ref
    

    到这里:

    AsRef::<str>::as_ref
    

    错误信息完全错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-07
      • 2019-07-16
      • 1970-01-01
      • 1970-01-01
      • 2017-12-15
      • 1970-01-01
      • 2013-03-01
      • 1970-01-01
      相关资源
      最近更新 更多