include_str!设置 "string literal" 路径

include_str! set "string literal" path

我必须在我的 Rust 二进制文件中发送一个 json 和一个 toml 文件。它是一个独立的应用程序,人们不想在 运行 时间传递配置文件。

include_str! 做我想做的。我可以写:

static SETTINGS_FILE_STR: &str = include_str!(r"../my_config/settings.toml");

有没有比r"../my_config/settings.toml"更好的文件路径写法?

我似乎无法从 use std::path::{Path, PathBuf};env 中的任何内容构建 string literal。我想知道我是否可以从 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,我可以使用构造函数或 Class 函数来实现我想要的。您可能已经猜到了,我是 Rust 的新手。

include_str! 是一个宏,因此在编译时执行。因为编译器在运行时还不知道 String 或某个静态变量的内容是什么,所以不能将 include_str!String 或静态变量一起使用。

然而,有一个相对于你的 crate root 引用文件的解决方法:你可以组合 env! and concat! with the environment variable CARGO_MANIFEST_DIR(由 Cargo 在编译时设置)来做你想做的。这两个宏都发出字符串文字,因此 include_str! 对它们很满意。

这会在你的 crate root 中输出 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);
}

如果要动态枚举文件名(例如包含目录中的所有文件),那么的方法也不起作用。

在这种情况下,我会压缩目录,将其包含为 include_bytes!,然后将其作为 zip 文件读取以枚举其内容并使用它们。

示例用例是将 ReactJS 或 Vue APP 的 dist 目录作为桌面应用程序包含在 webview rust 应用程序中。 github 中的示例代码将作为编辑。