我必须运送一个json
and a toml
我的 Rust 二进制文件中的文件。它是一个独立的应用程序,人们不想在运行时传递配置文件。
include_str!
做我想做的事。我可以写:
static SETTINGS_FILE_STR: &str = include_str!(r"../my_config/settings.toml");
有没有比写文件路径更好的方法r"../my_config/settings.toml"
?
我似乎无法构建一个string literal
从里面的任何东西use std::path::{Path, PathBuf};
or env
。我想知道我是否可以从中读到一些东西cargo.toml
文件。没有运气。
我总是打:
error: argument must be a string literal
--> src/main.rs:23:42
|
23 | static SETTINGS_STR: &str = include_str!(FANCY_PATH_TO_TOML_FILE);
| ^^^^^^^^^^^^
我无法执行以下操作,因为String
不是一个字符串字面量:
fn get_config_path() -> String {
let root_dir = project_root::get_project_root().with_context(|| format!("Failed to get project root directory"))?;
const path: PathBuf = root_dir.join("my_config/settings.toml");
path.to_string()
}
如果这是 C / Objective-C,我可以使用构造函数或类函数来实现我想要的。正如您可能已经猜到的,我是 Rust 新手。
include_str!
是一个宏,因此在编译时执行。因为编译器还不知道该内容是什么String
或者运行时的一些静态变量,你不能使用include_str!
with a String
或静态变量。
但是,有一种解决方法可以引用相对于您的板条箱根目录的文件:您可以组合env! https://doc.rust-lang.org/std/macro.env.html and concat! https://doc.rust-lang.org/std/macro.concat.html with 环境变量CARGO_MANIFEST_DIR https://doc.rust-lang.org/cargo/reference/environment-variables.html(由 Cargo 在编译时设置)做你想做的事。两个宏都发出字符串文字,所以include_str!
和他们在一起很开心。
这输出的内容my_config/settings.toml
在你的板条箱根内:
static SETTINGS_STR: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/my_config/settings.toml"));
fn main() {
println!("The config: {}", SETTINGS_STR);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)