2

The following doesn't compile:

pub fn main() {
    const IMG_PATH: &str = concat!("a", "b", "c");
    let img = include_str!(IMG_PATH);
}

It fails with an error that include_str requires a string literal:

error: argument must be a string literal
 --> src/main.rs:3:28
  |
3 |     let img = include_str!(IMG_PATH);
  |                            ^^^^^^^^

Constructing the string inside the include_str! seems to fix the compiler issue — it then complains about the path not being present in the filesystem so I suspect the former is resolved)

// works 
let img = include_str!(concat!("a", "b", "c"));

Why is this happening? As far as I understand concat operates statically and doesn't require doing anything at runtime. IMG_PATH is also a constant that should also be allocated at compile-time.

rustc 1.43.1 (8d69840ab 2020-05-04)

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
bergercookie
  • 2,542
  • 1
  • 30
  • 38
  • 3
    Macros are evaluated well before any understanding of what a constant is. – Optimistic Peach Jul 08 '20 at 02:08
  • You're not going to be able to mix runtime code and macro code like this. – tadman Jul 08 '20 at 02:12
  • Does this answer your question? [Can macros match against constant arguments instead of literals?](https://stackoverflow.com/questions/39349286/can-macros-match-against-constant-arguments-instead-of-literals) – Putnam Jul 08 '20 at 02:27
  • 1
    [The duplicates applied to your situation](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=5ebfbfb113881fba0a16f97184c39e53) – Shepmaster Jul 08 '20 at 02:33

0 Answers0