gpt4 book ai didi

rust - 使用AsRef时需要String的类型注释

转载 作者:行者123 更新时间:2023-12-03 11:48:34 25 4
gpt4 key购买 nike

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

最佳答案

啊,我刚发现它要我更改此设置:

AsRef::as_ref

对此:
AsRef::<str>::as_ref

错误消息是完全错误的。

关于rust - 使用AsRef时需要String的类型注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62121447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com