Hello. I`m reading The Book and stuck on a last task of first homework, where i need to print lyrics of the song. My question is not about algorithms or optimizations but only about assigning to the variable a value that is a concatenation of three strings.
I made a lot of different attempts, on a screenshot only the last one, neither of them compiled.
Please, help me.
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
OMG you answered so fast and so fully, thank you SO much!
I`m sorry if i interrupted some rules of using forum, i will learn them carefully.
Now my code compiles and i can continue my rust The Book journey. Very appreciate your answer.
It's not a rule, strictly speaking. Just a hint for how to ask better question, as it generally makes answering the question a lot easier, e.g. since one can copy the code and test it; and it makes the code more readable, too.
While you're at it, when you tried something and got an error, it might even make sense to also post the error message alongside the code. Spares the answerer the need to do it themself in case the compilation error makes understanding the problem easier.
Side note / clarification: The "string literal".to_owned()
that I used above is equivalent to writing something like String::from("string literal")
(which is used in the book IIRC).
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.