Using include! within an array


I am trying to include some external data into an array (for a test setup). In my tests, only the first element in the included data is actually parsed.

Sample code:

fn main() {
    let data = [ include!("main.txt") ];
    println!("{:?}", data);

The main.txt file contains:

1, 2, error

The resulting output is simply 1.

Am I doing something wrong, or is this a bug?

If I change the code to move the square brackets into the included file, it does work, but I’d like to avoid that if possible.


Interesting – it looks like it parses one expression and stops! If I change the file to “1 error” it still just produces [1], but “1 + error” complains about the unresolved name error. When you put the brackets in the file, that also lets the whole thing act as one expression.

The include! docs do say, “Parse a file as an expression or an item according to the context.” But I’m surprised that trailing data after the expression doesn’t cause an error, or at least a warning.


It makes sense that it should be limited to producing a single expression (unfortunately to @bruceg); this is a fundamental limitation of rust macros in general. AIUI, macros are constrained in such a way that the type of AST node a macro must produce is already known at the time it is invoked. (so rust expects an expression inside that array, and won’t take anything else for an answer)

I too am disturbed by the lack of error message. All I see on the tracker is this related issue which hasn’t received much commotion: