首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法使用Warp解决Rust编译错误

无法使用Warp解决Rust编译错误
EN

Stack Overflow用户
提问于 2021-11-18 05:29:53
回答 1查看 55关注 0票数 0

我正在尝试使用Rust Warp API使用一个小应用程序,但超级坚持构建代码。我正在努力学习this example here,但是我不能理解我做错了什么。有人能帮我一下吗?

代码语言:javascript
复制
async fn request_info(item: ItemObj) -> Result<impl warp::Reply, warp::Rejection> {

    let items = ItemConfig::new("data.toml");
    let item_info = items.find_session(&item.id);

    match item_info {
        Some(info) => {
            let json_reply = JsonReply {
                                 ItemId: item.id(),
                                 ItemDetail: item.detail(),
                                 EndPoint: info.get(),
                                 Port: info.get_port(),
                                 WebUrlPath: info.get_path_weburl(),
                            };
            // let json_str = serde_json::to_string(&json_reply);
            // Ok(warp::reply::with_status(json_str,http::StatusCode::OK,))
            Ok(warp::reply::json(&json_reply))

        }
        None => {
            Ok(warp::reply::with_status("", http::StatusCode::OK,))
        }
    }
}

#[tokio::main]
async fn main() {

    let resolver = warp::post()
        .and(warp::path("info_request"))
        .and(warp::path::end())
        .and(port_json()) 
        .and_then(request_info);

    warp::serve(resolver)
        .run(([127, 0, 0, 1], 8081))
        .await;
}

错误:

代码语言:javascript
复制
error[E0308]: mismatched types
  --> src/main.rs:50:16
   |
50 |               Ok(warp::reply::with_status("", 
   |  ________________^
51 | |                                         http::StatusCode::OK,))
   | |______________________________________________________________^ expected struct `Json`, found struct `WithStatus`
   |
   = note: expected struct `Json`
              found struct `WithStatus<&str>`

For more information about this error, try `rustc --explain E0308`.
warning: `resolver` (bin "resolver") generated 2 warnings
error: could not compile `resolver` due to previous error; 2 warnings emitted
EN

回答 1

Stack Overflow用户

发布于 2021-11-18 07:48:01

在匹配中,返回值必须相同。由于您不能确定返回值的大小,因此可以编写以下代码:

代码语言:javascript
复制
async fn request_info() -> Result<Box<dyn warp::Reply>, warp::Rejection> {
    let x = Some(5);

    match x {
        Some(x) => {
            let x = format!("{}", x);
            Ok(Box::new(warp::reply::json(&x)))
        }
        None => Ok(Box::new(warp::reply::with_status(
            "",
            warp::http::StatusCode::OK,
        ))),
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70014992

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档