Ben Chuanlong Du's Blog

It is never too late to learn.

Bundle Resource Files into a Rust Application

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

  1. The Rust macro include_str includes a UTF-8 encoded file as a string; the Rust macro include_bytes includes a file as a reference to a byte array. Both of those 2 macros load files into the Rust binary at compile time and consume memory at run time. It might not be a good idea to use them for large files!

  2. The Rust crate rust-embed provides custom derive macro which loads files into the Rust binary at compile time during release and loads the file from the fs during dev . It is the recommended way to embed many files into the Rust binary.

  3. The Rust crate include_dir is an evolution of the include_str and include_bytes macros for embedding an entire directory tree into your binary. It severs a similar purpose as the Rust crate rust-embed .

In [ ]:
If you need data files in your program, then:

include_bytes!() will hardcode data inside your executable. That's very useful if you need some internal data that the user doesn't need to touch.

Combine env::current_exe() with Path::join() and fs::canonicalize() to get absolute path relative to the executable. That's reasonable for data files distributed with the program, e.g. for a game.

Allow user to specify the path on command line

Use standard system directories for the data files
In [ ]:

Comments