Rust中的TOML解码?

时间:2017-07-18 14:26:22

标签: rust serde toml

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

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

有问题的代码示例如下:

//! 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 = "*"

我是否遗漏了某些东西,或者只是破坏了这个箱子解码的基本例子?

0 个答案:

没有答案