9

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Jan
  • 111
  • 1
  • 2
  • 4

1 Answers1

31

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:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 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". – Alex Spurling Dec 20 '22 at 22:40
  • @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](https://doc.rust-lang.org/book/ch04-03-slices.html#string-slices) / [Storing UTF-8 Encoded Text with Strings](https://doc.rust-lang.org/book/ch08-02-strings.html) and [Printing Values with println! Placeholders](https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#printing-values-with-println-placeholders). – Shepmaster Dec 21 '22 at 18:35
  • @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. – Shepmaster Dec 21 '22 at 18:37