How do println! macro captures variable?

Here is the code:

fn main() 
{
    let mut a: i32 = 57;
    let b: &mut i32 = &mut a;
    let c: &i32 = &b;
    //fun( b, c);     // error
    //fun(&mut b, &c);   //error too

    println!("{} {}", b, c );   // works
}

fn fun( b: &mut i32, c: &i32) { }

It seems to me that println! macro takes the variable(b, c) differently than the function fun. What could be the reasonable explanations behind it in simple English?

Thanks.

The macro does indeed capture the variables in a different way. That's because the macro actually expands to something that contains &b and &c rather than just containing b and c.

fn main() {
    let mut a: i32 = 57;
    let b: &mut i32 = &mut a;
    let c: &i32 = &b;

    fun(&b, &c);
    println!("{} {}", b, c);
}

fn fun(b: &&mut i32, c: &&i32) {}

Note that fun takes a reference to a reference in this example.

1 Like

You can actually read what macros expand to with cargo-expand or in the playground under Tools > Expand Macros.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.