10

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?

1 Answer 1

33

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:

Sign up to request clarification or add additional context in comments.

3 Comments

Could you please point to where in the The Rust Programming Language book it points this common pitfall? I admit, I haven't read it all but I have started at the beginning and methodically worked my way through it and have yet to reach the point where it explains why the println! macro cannot accept "unsized types".
@AlexSpurling that's not quite what the answer means. The answer is saying "you should read the book to see how to pass strings around / invoke println!". That's covered in String Slices / Storing UTF-8 Encoded Text with Strings and Printing Values with println! Placeholders.
@AlexSpurling The question you are asking is more fundamentally "why can't a function accept an unsized type" because println expands to function calls. That's because it's not possible to calculate the amount of stack space at compile time because the size isn't known until runtime.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.