[Solved] Format! to str (type ascription is experimenal)


Hi all! This is my first post here, and hope it’s not the last one!

I’m trying to write a macro that does a format! ending with .as_str(). Here it goes:

macro_rules! mkstr {
  ($fmt:expr) => (format!($fmt).as_str());
  ($fmt:expr, $($args:tt)*) => (format!($fmt, $($args:tt)*).as_str());

If I don’t use it compiles, as it does when using it with a single parameter, but when I used more I get an error saying type ascription is experimental (see issue #23416), which I don’t understand.

What’s going on?


You have $args:tt in the expansion, but you want $args


Type ascription is an unstable feature that lets you do

foo.enumerate().collect(): Vec<_>

instead of

let x: Vec<_> = foo.enumerate().collect();

i.e. use a colon to state the type of some expression without assigning it to a variable. See the RFC for more about the motivation.

Sometimes when your program has misplaced colons, the compiler sees it as type ascription.

In addition to the colon that @bluss pointed out it looks like you also have an extra colon on the left-hand side in $($args::tt)*. It should be $($args:tt),* with one fewer colon and a comma to mean they are comma-separated.


@dtolnay I fixed the double colon, as it was not present on the code I’m writing, only on the post :sweat_smile:

Thank you very much to both of you for your help, it’s working now :slight_smile: