18
17

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で設定ファイルの内容をグローバル変数に保存する

Last updated at Posted at 2020-10-04

Rustで設定ファイルの内容をグローバル変数に保存する

設定ファイル .env を読み込んでグローバルな変数に保持する。

.env

ADDRESS=localhost
PORT=6379

環境

  • Ubuntu 20.04
  • Rust 1.46.0

使用するcrate

[dependencies]
#.envファイルの内容を環境変数として読み込む
dotenv = "0.15.0"
# .envの内容をConfigに保存するcrate
config = "0.10.1"
# 実行時にstatic変数を初期化するcrate
lazy_static = "1.4.0"
serde = {version = "1.0.116", features = ["derive"]}

コード

extern crate lazy_static;

use config::ConfigError;
use dotenv::dotenv;
use lazy_static::lazy_static;
use serde::Deserialize;

/// .envの内容を保存するstruct
#[derive(Deserialize, Debug)]
pub struct Config {
    pub address: String,
    pub port: i32,
}

impl Config {
    /// 環境変数からデータを読み込む
    pub fn from_env() -> Result<Self, ConfigError> {
        let mut cfg = config::Config::new();
        cfg.merge(config::Environment::new())?;
        cfg.try_into()
    }
}

/// static変数の初期化
lazy_static! {
    static ref CONFIG: Config = {
        dotenv().ok();
        Config::from_env().unwrap()
    };
}

fn main() {
    println!("address: {}", CONFIG.address);
    println!("port: {}", CONFIG.port);
}
18
17
1

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
18
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?