Search code examples
stringrustmacros

How to fix "argument must be a string literal" with include_bytes!()?


I want to compile this test file but I am getting an error:

const TEST: &'static str = "Test.bin";

fn main() {
    let x = include_bytes!(TEST);
}
error: argument must be a string literal
 --> test.rs:4:22
  |
4 |     let x = include_bytes!(TEST);
  |                      ^^^^

How to fix this?


Solution

  • The macro expects a string literal, so it cannot be a variable:

    include_bytes!("Test.bin");
    

    Alternatively you could create a macro that will expand into the desired value too:

    macro_rules! test_bin {
        // `()` indicates that the macro takes no argument.
        () => {
            "Test.bin"
        };
    }
    
    fn main() {
        let x = include_bytes!(test_bin!());
    }
    

    Playground