首页 > 解决方案 > 如何在 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();

我正在编写一个 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);

标签: rust

解决方案


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

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

推荐阅读