如何将文件内容包含在 Rust 编译的二进制文件中?

7
const fn get_dockerfile() -> String {
    let mut file_content = String::new();
    let mut file = File::open("dockers/PostgreSql").expect("Failed to read the file");
    file.read_to_string(&mut file_content);
    file_content
}

const DOCKERFILE: String = get_dockerfile();

我正在编写一个Rust脚本来管理Docker操作。

  1. 我希望在我的二进制可执行文件中包含docker文件内容。
  2. 我认为通过将这个内容分配到一个const变量中,我可以实现这个目标,但是我遇到了这个错误:
error[E0723]: mutable references in const fn are unstable
 --> src/main.rs:9:5
  |
9 |     file.read_to_string(&mut file_content);
2个回答

14

你可以使用 include_str!() 宏:

let dockerfile = include_str!("Dockerfile");

这将会把文件内容嵌入二进制文件中,作为一个字符串。变量dockerfile被初始化为指向该字符串的指针。由于这种初始化基本上是免费的,所以甚至不必将其设置为常量。

如果你的文件不是有效的UTF-8编码,你可以使用include_bytes!()代替。


12

使用include_str!宏在编译时包含来自文件的字符串。

const DOCKERFILE: &str = include_str!("dockers/PostgreSql");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接