Rust 1.70 中未找到 Trait 实现

ZJa*_*ume 4 traits rust

我使用的是srx crate,它在 Rust 1.61 下工作正常。现在,我更新到 Rust 1.70,但它找不到FromStr特征实现。

在 1.61 中有效但在 1.70 中无效的示例代码:

use std::fs::read_to_string;
use std::fs;
use std::str::FromStr;
use srx::SRX;

fn main() {
    let srx_file = "../data/language_tool.segment.srx";
    let _srx2: SRX = read_to_string(srx_file).expect("").parse().unwrap();
    let _srx1 = SRX::from_str(&fs::read_to_string(srx_file).unwrap())?;
}
Run Code Online (Sandbox Code Playgroud)

和编译器错误:

error[E0277]: the trait bound `SRX: FromStr` is not satisfied
 --> src/main.rs:8:58
  |
8 |     let _srx2: SRX = read_to_string(srx_file).expect("").parse().unwrap();
  |                                                          ^^^^^ the trait `FromStr` is not implemented for `SRX`
  |
  = help: the following other types implement trait `FromStr`:
            IpAddr
            Ipv4Addr
            Ipv6Addr
            NonZeroI128
            NonZeroI16
            NonZeroI32
            NonZeroI64
            NonZeroI8
          and 31 others
note: required by a bound in `core::str::<impl str>::parse`
 --> /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/core/src/str/mod.rs:2352:5

error[E0599]: no function or associated item named `from_str` found for struct `SRX` in the current scope
 --> src/main.rs:9:22
  |
9 |     let _srx1 = SRX::from_str(&fs::read_to_string("data/segment.srx").unwrap())?;
  |                      ^^^^^^^^ function or associated item not found in `SRX`

warning: unused import: `std::str::FromStr`
 --> src/main.rs:3:5
  |
3 | use std::str::FromStr;
  |     ^^^^^^^^^^^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

Some errors have detailed explanations: E0277, E0599.
For more information about an error, try `rustc --explain E0277`.
Run Code Online (Sandbox Code Playgroud)

库中的特征在这里实现。

我对 Rust 还很陌生,所以我不确定我是否做错了什么,或者库没有为新的 Rust 版本正确实现它。

Jon*_*der 5

如果您查看FromStrfor的特征实现SRX,您会发现它受到一个功能的保护:

#[cfg_attr(docsrs, doc(cfg(feature = "from_xml")))] // only implement FromStr if the from_xml feature is enabled
impl FromStr for SRX {
    type Err = Error;
    fn from_str(string: &str) -> Result<Self, Self::Err> {
        schema::from_str(string)
            .map_err(Error::from)
            .and_then(SRX::try_from)
    }
}
Run Code Online (Sandbox Code Playgroud)

文档中也用紫色框指出了这一点:

仅板条箱功能from_xml支持此功能。

要解决此问题,您需要在文件中启用 cratefrom_xml的功能:srxCargo.toml

[dependencies]
srx = { version = "0.1", features = ["from_xml"] }
Run Code Online (Sandbox Code Playgroud)