【问题标题】:no function or associated item named `from_str` found for type `hyper::mime::Mime`找不到类型为“hyper::mime::Mime”的名为“from_str”的函数或关联项
【发布时间】:2018-07-17 06:37:32
【问题描述】:

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

extern crate hyper;

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

错误:

error[E0599]: no function or associated item named `from_str` found for type `hyper::<unnamed>::Mime` in the current scope

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

【问题讨论】:

标签: rust


【解决方案1】:

您收到此错误是因为,毫无疑问,Mime 上没有定义 from_str 方法。为了解析像Mime::from_str 这样的名称,from_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;`

然而,在这个特殊的情况下,更常见的是使用FromStr,而不是直接调用from_str,而是间接使用str上的parse方法,如FromStr's documentation提及。

let test1: hyper::mime::Mime = "text/html+xml".parse().unwrap();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 2018-09-13
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 2011-01-13
    相关资源
    最近更新 更多