英文:
How to share .env values loaded from API project to lib project in rust?
问题
我是新手对Rust不太熟悉,我在尝试加载.env文件中的设置/配置值并在Rust依赖项(如库项目)中轻松共享这些值方面遇到了困难。这是项目结构:
- apiProject
-- \src
-- \src\main.rs
-- .env
-- Cargo.toml
- libProject
-- \src
-- \src\lib.rs // <-- 需要共享设置的地方。
-- Cargo.toml
我尝试将值推送到环境中,然后在库项目中临时提取这些值,但什么都得不到。我使用了一些println()命令来计算环境变量的变化前后的数量,并注意到值没有增加。
英文:
I am  new to rust and am struggling with how to load up a .env file with settings/config values and then share this easily with Rust dependencies such as library projects. This is the project structure:
- apiProject
-- \src
-- \src\main.rs
-- .env
-- Cargo.toml
- libProject
-- \src
-- \src\lib.rs // <-- settings need sharing into here.
-- Cargo.toml
I have tried pushing the values into the environment and then ad hoc pulling the values in the library project but I get nothing. I used some println() commands to count the before and after environment variable count and noticed the value was not incrementing.
答案1
得分: 1
以下是代码部分的中文翻译:
这里是一个使用 dotenvy crate 从 .env 文件加载环境变量的示例,在你的 API 项目的 main() 函数中。
api_project/src/main.rs 中的主函数:
fn main() {
    dotenvy::dotenv().unwrap();
    println!("API 项目调用库函数。");
    lib_project::say_hello();
}
然后,当 main() 调用来自 lib_project crate 的库函数时,环境变量就可用了。lib_project/src/lib.rs 中定义的库函数:
pub fn say_hello() {
    let name = get_name();
    println!("你好,{name} 来自库项目");
}
fn get_name() -> String {
    std::env::var("MY_NAME").unwrap_or("匿名".to_owned())
}
示例:
$ cat .env 
MY_NAME="Linus Torvalds"
然后,运行二进制 crate 会显示该变量值从库项目中打印出来:
$ cargo run -q
从 .env 文件加载环境变量
API 项目调用库函数。
你好,Linus Torvalds 来自库项目
API 项目完成。
请注意,这是代码的翻译,仅包括代码部分,不包括额外的内容。
英文:
Here's an example of loading environment variables from a .env file using the dotenvy crate in your API project's main() function.
Main function from api_project/src/main.rs:
fn main() {
    dotenvy::dotenv().unwrap();
    println!("API Project calling into the library.");
    lib_project::say_hello();
}
Then when main() calls a library function from the lib_project crate, the environment variables are available. Library function defined in lib_project/src/lib.rs:
pub fn say_hello() {
    let name = get_name();
    println!("Hello, {name} from the Library Project");
}
fn get_name() -> String {
    std::env::var("MY_NAME").unwrap_or("Anonymous".to_owned())
}
Example:
$ cat .env 
MY_NAME="Linus Torvalds"
Then, running the binary crate shows this variable value being printed from the library project:
$ cargo run -q
Loaded environment variables from .env file
API Project calling into the library.
Hello, Linus Torvalds from the Library Project
API Project done.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论