rust 用dotenv设置变量

来源:C 语言 / 时间:2026-09-19

rust 使用 dotenv 设置变量
创建一个新的 Rust 项目
cargo new
如创建 env 项目

cargo new env

ls 项目
$ ls -lah

Cargo.toml
.env
.git
.gitignore
src

环境变量 .env 文件内容

RUN_PORT=8088
LOG_LEVEL=debug
API_KEY=your_api_key

项目 src 目录下
src/main.rs
文件内容

use std::env;
use dotenv::dotenv;

fn main() {
	dotenv().ok();
	
    for (k, v) in env::vars() {
        println!("{}: {}", k, v);
    }
	
    if let Ok(value) = env::var("RUN_PORT") {
        println!("The RUN_PORT environment variable is: {}", value);
    } else {
        println!("The RUN_PORT environment variable is not set.");
    }	
	
}


项目运行

cargo run

…
RUN_PORT: 8088
LOG_LEVEL: debug
API_KEY: your_api_key
The RUN_PORT environment variable is: 8088

上一篇: LuaJIT

下一篇: Sumatra PDF Plus

客服