1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

RustでtomlファイルをstructにDeserialzeする

Last updated at Posted at 2020-06-24

やりたかったこと

tomlファイルの内容を、structに追加したかった

Cargo.toml

[dependencies]
toml = "0.5.6"
serde_derive = "1.0.113"

読み込むtoml

# ./config/local.toml
[mongo_db]
name = "hoge"
age = 120

実装

※コメントで頂いたコードのほうがいいので、そちらの方を参照してください!!

#[derive(Debug, Deserialize)]
pub struct Config {
    pub mongo_db: MongoDb,
}

// 適当なsturctなのでごめんなさい
#[derive(Debug, Deserialize)]
pub struct MongoDb {
    pub name: String,
    pub age: i32,
}

fn main() {
    let config = toml::deserial_toml_file::<Config>("./config/local.toml", &mut String::from(""))?;
    println!("config is {:?}", config);
}

// deserial_toml_file tomlのfileをstructにdeserializeする
pub fn deserial_toml_file<'a, T>(path: &'a str, file_str: &'a mut String) -> Result<T>
where
    T: Deserialize<'a>,
{
    *file_str = file::read_file(path)?;

    let obj = toml::from_str::<T>(file_str)?;

    Ok(obj)
}

感想

ジェネリクスで実装したらlifetimeのerrorが発生したため、
file_strを無理やり引数に書きました、
もっといい方法があればコメントもらいたいです...

1
1
3

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?