Is there a way to pass named arguments to format macros without repeating the variable names?

Viewed 2990

With new versions of Rust, you can simplify structure initialization like this:

Foo {
    a: a,
    b: b,
}

to this

Foo { a, b }

Is it possible to do something similar for format!/println!-like macros?

For now I need to write it like this:

let a = "a";
let b = "b";
write!(file, "{a} is {b}", a = a, b = b).unwrap();

Is it possible to write my own macros with an API like this:

let a = "a";
let b = "b";
my_write!(file, "{a} is {b}", a, b).unwrap();
2 Answers

As of 1.5 this is the closest you can get natively.

my_write!(file, "{} is {}", a, b).unwrap();

Additionally as Shepmaster pointed out my answer will eventually become obsolete (I'll try to remember to remove it when that happens). If you want to keep an eye on the (to be implemented) syntax they propose you can check this github ticket they linked

Related