Spiderman
Spiderman

Reputation: 2087

How to include file contents in Rust compiled binary?

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);

Upvotes: 10

Views: 6410

Answers (2)

hoz
hoz

Reputation: 316

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

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

Upvotes: 14

Sven Marnach
Sven Marnach

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

Related Questions