10
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.

  1. I want to include docker-file content in my binary executable.
  2. I thought by assigning that content into a 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);

2 Answers 2

17

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.

Sign up to request clarification or add additional context in comments.

Comments

14

Use the include_str! macro to include strings from files at compile time.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.