LoginSignup
4
5

More than 3 years have passed since last update.

RustでTOMLをファイルに書き出す・structに読み込む

Last updated at Posted at 2020-01-03

動機

設定ファイルをsetting.tomlのような形にして外部に吐き出しておいて,あとで読み込みたい.
RustでTOMLを扱うにはtoml-rsを使う.本稿では併せてファイルの入出力を行う.

環境

環境
$ rustc --version
rustc 1.40.0 (73528e339 2019-12-16)
$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.15
BuildVersion:   19A603

最終結果

ファイル構成
$ tree
.
├── Cargo.lock
├── Cargo.toml
└── src
   └── main.rs

Cargo.toml
[package]
name = "toml-handle"
version = "0.1.0"
authors = ["Scstechr <scstechr@email.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
serde = { version = "1.0.104", features = ["derive"] }
toml = "0.5.5"

src/main.rs
extern crate serde;
extern crate toml;

use serde::{Deserialize, Serialize};
use std::fs::{self, File};
use std::io::Write;

#[derive(Debug, Serialize, Deserialize)]
struct Setting {
    os: String,
    version: f32,
    users: Vec<String>,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Definition of struct instant
    let setting = Setting {
        os: "Mac OS X".into(),
        version: 10.15,
        users: vec!["John Doe".into(), "Alice Carter".into()],
    };
    println!("\n#Original:\n{:#?}", setting);

    // Write TOML to file
    let mut file = File::create("Setting.toml")?;
    let toml = toml::to_string(&setting).unwrap();
    write!(file, "{}", toml)?;
    file.flush()?;
    println!("\n#TOML:\n{}", toml);

    // Read file and parse to Setting
    let foo: String = fs::read_to_string("Setting.toml")?;
    let setting: Result<Setting, toml::de::Error> = toml::from_str(&foo);
    match setting {
        Ok(p) => println!("#Parsed TOML:\n{:#?}", p),
        Err(e) => panic!("Filed to parse TOML: {}", e),
    }
    Ok(())
}

出力
$ cargo run
   Compiling toml-handle v0.1.0 (/Users/Scstechr/Works/projects/toml-handle)
    Finished dev [unoptimized + debuginfo] target(s) in 1.54s
     Running `target/debug/toml-handle`

#Original:
Setting {
    os: "Mac OS X",
    version: 10.14,
    users: [
        "John Doe",
        "Alice Carter",
    ],
}

#TOML:
os = "Mac OS X"
version = 10.14
users = ["John Doe", "Alice Carter"]

#Parsed TOML:
Setting {
    os: "Mac OS X",
    version: 10.14,
    users: [
        "John Doe",
        "Alice Carter",
    ],
}

おわり

TODO

解説を追記する.

参考

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5