Reputation: 121
I am currently learning Rust (mostly from scratch) and now I want to add two strings together and print them out. But that is not as easy as in other languages. Here's what I've done so far (also tested with print!
):
fn sayHello(id: str, msg: str) {
println!(id + msg);
}
fn main() {
sayHello("[info]", "this is rust!");
}
The error I get is a little bit weird.
error: expected a literal
--> src/main.rs:2:14
|
2 | println!(id + msg);
| ^^^^^^^^
How can I solve this so that [info] this is rust will be printed out?
Upvotes: 10
Views: 23359
Reputation: 432239
Don't try to learn Rust without first reading the free book The Rust Programming Language and writing code alongside.
For example, you are trying to use str
, which is an unsized type. You are also trying to pass a variable to println!
, which requires a format string. These things are covered early in the documentation because they trip so many people up. Please make use of the hard work the Rust community has done to document these things!
All that said, here's your code working:
fn say_hello(id: &str, msg: &str) {
println!("{}{}", id, msg);
}
fn main() {
say_hello("[info]", "this is Rust!");
}
I also changed to use snake_case
(the Rust style).
See also:
Upvotes: 33