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

Spi*_*man 1 rust

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();
Run Code Online (Sandbox Code Playgroud)

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

  1. 我想在我的二进制可执行文件中包含 docker-file 内容。
  2. 我认为通过将该内容分配给一个const变量我可以实现这一点,但我收到此错误:
error[E0723]: mutable references in const fn are unstable
 --> src/main.rs:9:5
  |
9 |     file.read_to_string(&mut file_content);
Run Code Online (Sandbox Code Playgroud)

hoz*_*hoz 6

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

const DOCKERFILE: &str = include_str!("dockers/PostgreSql");
Run Code Online (Sandbox Code Playgroud)


Sve*_*ach 6

您可以使用include_str!()宏:

let dockerfile = include_str!("Dockerfile");
Run Code Online (Sandbox Code Playgroud)

这会将文件内容作为字符串嵌入二进制文件中。该变量dockerfile被初始化为指向该字符串的指针。甚至没有必要让它成为一个常量,因为这个初始化基本上是免费的。

如果您的文件不是有效的 UTF-8,则可以include_bytes!()改用。