String concatenation on variable assignment

The concat! macro is absolutely not the right tool for this job. It's a macro thats simply rewriting your code so that code like concat!("foo", "bar") would be re-written into "foobar" at compile-time.

For concatenating a list of strings at runtime take a look at the concat method on slices.

E.g.

["One the ", number_in_words[i], " day of Christmas\nMy true love sent to me\n"].concat()

You could also fix the typo of "One" to "On", I guess.

Alternatively, you can also use the format! macro here to achieve a similar effect

format!("One the {} day of Christmas\nMy true love sent to me\n", number_in_words[i]);

Note that either of these approaches produces an owned String, instead of a borrowed &str. This means that if you want to put them into the same array as some literals, you'll have to adapt the type of the array to contain String, and convert the literals. E.g. if song_lyics will contain the concatenated strings, you could do

let mut song_lyrics = <[String; 12]>::default();

to define and initialize the array with owned strings as elements, and you can do something like

song_lyrics[0] = "On the first day of Christmas\nMy true love sent to me\n".to_owned();

in order to convert a string literal (which is of a borrowed &str type) into an owned String.


Side-note, it's generally appreciated if you post code as text and not as screenshots. To learn how to post properly formatted code blocks, see this thread: Forum Code Formatting and Syntax Highlighting

2 Likes