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 操作。
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)
使用include_str!宏在编译时包含文件中的字符串。
const DOCKERFILE: &str = include_str!("dockers/PostgreSql");
Run Code Online (Sandbox Code Playgroud)
您可以使用include_str!()宏:
let dockerfile = include_str!("Dockerfile");
Run Code Online (Sandbox Code Playgroud)
这会将文件内容作为字符串嵌入二进制文件中。该变量dockerfile被初始化为指向该字符串的指针。甚至没有必要让它成为一个常量,因为这个初始化基本上是免费的。
如果您的文件不是有效的 UTF-8,则可以include_bytes!()改用。
| 归档时间: |
|
| 查看次数: |
398 次 |
| 最近记录: |