Reputation: 2087
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();
I'm writing a Rust script to manage docker operations.
const
variable I could achieve this but I am getting this error:error[E0723]: mutable references in const fn are unstable
--> src/main.rs:9:5
|
9 | file.read_to_string(&mut file_content);
Upvotes: 10
Views: 6410
Reputation: 316
Use the include_str!
macro to include strings from files at compile time.
const DOCKERFILE: &str = include_str!("dockers/PostgreSql");
Upvotes: 14
Reputation: 601559
You can use the include_str!()
macro:
let dockerfile = include_str!("Dockerfile");
This will embed the file contents in the binary as a string. The variable dockerfile
is initialized as a pointer to this string. It's not even necessary to make it a constant, since this initialization is basically free.
If your file isn't valid UTF-8, you can use include_bytes!()
instead.
Upvotes: 17