1

我正在尝试使用 TOML crate 将配置文件读入 Rust 结构。我收到了一个似乎与我的代码无关的一致 Serde 错误,因此我决定尝试 TOML 文档中的解码示例,令我惊讶的是,它未能以完全相同的错误构建。

我已经向 crate 维护者提交了一个问题,但我有一种唠叨的感觉,我可能会遗漏一些东西。

有问题的代码示例如下:

//! An example showing off the usage of `Deserialize` to automatically decode
//! TOML into a Rust `struct`

#![deny(warnings)]

extern crate toml;
extern crate serde;
#[macro_use]
extern crate serde_derive;

/// This is what we're going to decode into. Each field is optional, meaning
/// that it doesn't have to be present in TOML.
#[derive(Debug, Deserialize)]
struct Config {
    global_string: Option<String>,
    global_integer: Option<u64>,
    server: Option<ServerConfig>,
    peers: Option<Vec<PeerConfig>>,
}

/// Sub-structs are decoded from tables, so this will decode from the `[server]`
/// table.
///
/// Again, each field is optional, meaning they don't have to be present.
#[derive(Debug, Deserialize)]
struct ServerConfig {
    ip: Option<String>,
    port: Option<u64>,
}

#[derive(Debug, Deserialize)]
struct PeerConfig {
    ip: Option<String>,
    port: Option<u64>,
}

fn main() {
    let toml_str = r#"
        global_string = "test"
        global_integer = 5
        [server]
        ip = "127.0.0.1"
        port = 80
        [[peers]]
        ip = "127.0.0.1"
        port = 8080
        [[peers]]
        ip = "127.0.0.1"
    "#;

    let decoded: Config = toml::from_str(toml_str).unwrap();
    println!("{:#?}", decoded);
}

我在构建时遇到的错误如下:

error[E0277]: the trait bound `Config: serde::de::Deserialize<'_>` is not satisfied
  --> src/main.rs:51:27
   |
51 |     let decoded: Config = toml::from_str(toml_str).unwrap();
   |                           ^^^^^^^^^^^^^^ the trait `serde::de::Deserialize<'_>` is not implemented for `Config`
   |
   = note: required by `toml::from_str`

我尝试使用以下工具链构建它:

  • rustc 1.20.0-nightly (2652ce677 2017-07-17)

  • rustc 1.18.0 (03fc9d622 2017-06-06)

我的 Cargo.toml 包括以下内容:

[dependencies]
serde = "*"
serde_derive = "*"
toml = "*"

我是否遗漏了某些东西,或者用这个板条箱进行解码的基本示例是否被破坏了?

4

0 回答 0