Timmmm
Timmmm

Reputation: 96801

Type annotations needed for String when using AsRef

I'm using Warp like this:


#[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
        })
    ...

If I compile it gives this error:

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`

This is really weird. What does it mean consider giving this closure parameter a type? Doesn't it already have a type? Even weirder, if I comment out this line:

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

Then it compiles! Even though that line apparently has nothing to do with the topic parameter. What's going on?

Upvotes: 0

Views: 896

Answers (1)

Timmmm
Timmmm

Reputation: 96801

Ah I just figured out it wanted me to change this:

AsRef::as_ref

to this:

AsRef::<str>::as_ref

The error message is just totally wrong.

Upvotes: 1

Related Questions