Trait std::convert::from not 实现 hyper::body:<String>:body


lazy_static::lazy_static! {
static ref file_data: String = fs::read_to_string("static/login.html").expect("unable to read from static/login.html");
}
#[tokio::main]
async fn main() {
// code omitted
let login = warp::path("login").map(move || warp::reply::html(file_data));
// code omitted
}

编译错误:

error[E0277]: the trait bound `hyper::body::body::Body: std::convert::From<file_data>` is not satisfied
--> src/main.rs:45:49
|
45  |     let login = warp::path("login").map(move || warp::reply::html(file_data));
|                                                 ^^^^^^^^^^^^^^^^^ the trait `std::convert::From<file_data>` is not implemented for `hyper::body::body::Body`
| 
::: /home/ichi/.cargo/registry/src/github.com-1ecc6299db9ec823/warp-0.2.3/src/reply.rs:170:11
|
170 |     Body: From<T>,
|           ------- required by this bound in `warp::reply::html`
|
= help: the following implementations were found:
<hyper::body::body::Body as std::convert::From<&'static [u8]>>
<hyper::body::body::Body as std::convert::From<&'static str>>
<hyper::body::body::Body as std::convert::From<bytes::bytes::Bytes>>
<hyper::body::body::Body as std::convert::From<std::borrow::Cow<'static, [u8]>>>
and 4 others

我正试图将String传递给闭包。根据文档,From<String>是为hyper::body::Body实现的,而file_data是类型String。那么为什么我会出现这个错误呢?

来自lazy_static

对于给定的static ref NAME: TYPE = EXPR;,宏生成一个实现Deref<TYPE>的唯一类型,并将其存储在名为NAME的静态中。(属性最终附加到此类型。(

也就是说,变量的类型是而不是TYPE

这就是为什么你看到错误

the trait `std::convert::From<file_data>` is not implemented for `hyper::body::body::Body`
^^^^^^^^^

您可能更幸运的是显式地取消引用或克隆全局变量:warp::reply::html(&*file_data)warp::reply::html(file_data.clone())

这里的问题是lazy_static创建了一个引用您的数据的包装器类型,而hyper不知道如何处理它。您可以使用file_data.clone()克隆引用的数据并从中构造主体,但在这种情况下,实际上有一个更简单的方法。由于您的字符串有一个固定值,并且Body实现了From<&'static str>,因此您实际上根本不需要堆分配的Stringlazy_static:您可以使用以下代码,该代码只使用可以直接使用的常量字符串切片。

const FILE_DATA: &str = "test";
#[tokio::main]
async fn main() {
// code omitted
let login = warp::path("login").map(move || warp::reply::html(FILE_DATA));
// code omitted
}

相关内容

最新更新