Embed Directive in Rust

Here’s the translation of the Go code to Rust, along with explanations in Markdown format suitable for Hugo:

Rust doesn’t have a direct equivalent to the //go:embed directive, but we can achieve similar functionality using the include_str! and include_bytes! macros. For more complex embedding, we can use the rust-embed crate.

use std::fs;

// Use the include_str! macro to embed the contents of a file as a &'static str
const FILE_STRING: &str = include_str!("folder/single_file.txt");

// Use the include_bytes! macro to embed the contents of a file as a &'static [u8]
const FILE_BYTE: &[u8] = include_bytes!("folder/single_file.txt");

fn main() {
    // Print out the contents of 'single_file.txt'
    print!("{}", FILE_STRING);
    print!("{}", std::str::from_utf8(FILE_BYTE).unwrap());

    // Retrieve some files from the folder
    let content1 = fs::read_to_string("folder/file1.hash").unwrap();
    print!("{}", content1);

    let content2 = fs::read_to_string("folder/file2.hash").unwrap();
    print!("{}", content2);
}

In this Rust version:

  1. We use the include_str! macro to embed the contents of a file as a &'static str.
  2. We use the include_bytes! macro to embed the contents of a file as a &'static [u8].
  3. For reading multiple files or folders, we use the standard fs module to read files at runtime.

To run this example, you would need to create the folder and files as described in the original example:

$ mkdir -p folder
$ echo "hello rust" > folder/single_file.txt
$ echo "123" > folder/file1.hash
$ echo "456" > folder/file2.hash

Then you can run the Rust program:

$ rustc embed_example.rs
$ ./embed_example
hello rust
hello rust
123
456

Note that this approach embeds the files at compile-time for single_file.txt, but reads the .hash files at runtime. For more complex embedding scenarios, including embedding entire directories, you might want to use a crate like rust-embed which provides similar functionality to Go’s embed.FS.

Remember that the Rust approach to embedding files is different from Go’s, and the exact method you choose may depend on your specific use case and requirements.