rust - 使用 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
即使该行显然与参数无关。这是怎么回事?
解决方案
啊,我刚刚发现它要我改变这个:
AsRef::as_ref
对此:
AsRef::<str>::as_ref
错误消息是完全错误的。
推荐阅读
- entity-framework - 如何在 Entity Framework Core 中创建运行时迁移
- php - 测试 API 调用,它调用另一个 URL
- mysql - 为什么我的公用表表达式查询不适用于 Mysql?
- python - 从 Python 调用多个 .exe
- python - 如何在 pythonanywhere 上运行 django-made venv?
- regex - 正则表达式,崇高语法文件,匹配除特定组之外的特定字符之后的所有内容
- javascript - 使用带有猫鼬函数的 Promise
- c# - 如何从 program.cs 中的 appsettings 中读取 UrlPrefixes - asp.net core 3.1
- c# - 无法使用文件路径将通用 base64 图像发送到 API
- verilog - 为什么这个输出会延迟一下?