Anyway around format argument must be string literal?

I have the same "format argument must be string literal" issue described here which was closed in 2019

I would like to programmatically add string a from a struct field to format!(a, b) to take advantage of string interpolation.

As per the referenced earlier post, this seemed not possible in 2019, but that's quite some time ago... are there any ways around this since then?

Thanks in advance for any help!

For the built-in formatting there is no other option. It really must be a literal.

You will have to find another solution, e.g. use .replace to perform your own substitution, and/or call .to_string() on values yourself, or combine multiple smaller format! or format_args! together.

1 Like

The compiler needs to know the format argument at compile time to be able to parse it and generate code which does the formatting for that specific format argument. You could use something like the runtime-format crate though.

2 Likes

A couple other crates are const_format (this has the most downloads) and formatx.

1 Like

@kornel thanks for the advice that this is still a hard constraint and for the suggestion to use replace which I eventually did:

let result = self.archive.replace("<VERSION>", &self.version);

where self.archive is the url template of a GitHub release with a <VERSION> part to be replaced.

@bjorn3 Thanks for clarification that for format!, the "compiler needs to know the argument at compile time". I thought if the arguments were compile time strings or even static strings the issue would be resolved, but it looks like the format! format string can only be a 'literal' in this case.

Also thanks for the reference to the runtime-format crate. This is precisely what I was looking for (since I actually do have runtime arguments), but I just ended up using String.replace as per an earlier suggestion in order not to add another crate dependency.

@jumpnbrownweasel Thanks for the references to const_format for compile-time formatting and formatx for runtime formatting.These look great.

Wow, so many good distinct solution, the rust ecosystem has really grown in leaps and bounds since 2019 :grinning:

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.