找不到类型为 `hyper::mime::Mime` 的名为 `from_str` 的函数或关联项

Ole*_*egu 5 rust

我正在使用 Hyper 0.11,它重新导出板条箱“mime”。我正在尝试从字符串创建 MIME 类型:

extern crate hyper;

fn main() {
    let test1 = hyper::mime::Mime::from_str("text/html+xml").unwrap();
}
Run Code Online (Sandbox Code Playgroud)

错误:

extern crate hyper;

fn main() {
    let test1 = hyper::mime::Mime::from_str("text/html+xml").unwrap();
}
Run Code Online (Sandbox Code Playgroud)

为什么会出现这个错误,原因是什么?如何解决?

tre*_*tcl 8

您会收到此错误,因为确实没有from_str在 上定义方法Mime。为了解析像这样的名称Mime::from_strfrom_str必须是Mime(不是特征的一部分)的固有方法,或者是在使用它的地方的范围内的特征的一部分。FromStr不在范围内,所以你会得到一个错误——尽管错误消息甚至告诉你出了什么问题以及如何解决它:

error[E0599]: no function or associated item named `from_str` found for type `hyper::<unnamed>::Mime` in the current scope
 --> src/main.rs:3:13
  |
3 | let test1 = hyper::mime::Mime::from_str("text/html+xml").unwrap();
  |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = help: items from traits can only be used if the trait is in scope
  = note: the following trait is implemented but not in scope, perhaps add a `use` for it:
          candidate #1: `use std::str::FromStr;`
Run Code Online (Sandbox Code Playgroud)

但是,在这种特殊情况下,更常见的是FromStr不是通过from_str直接调用,而是通过parseon 方法间接调用str,正如FromStr文档中提到的那样。

let test1: hyper::mime::Mime = "text/html+xml".parse().unwrap();
Run Code Online (Sandbox Code Playgroud)