How to concat strings

I'm trying to change h from Hello to Hello, World using combination of 2 words, I tried 2 macros, format! and concat! but both faied

fn main() {
   let mut h = "Hello";
   let w = "World";
   //h = format!("{}, {}",h, w);
   h= concat!(h, ", ", w);
   println!("{}", h);
}

For format! I got this error:

error[E0308]: mismatched types
 --> src/main.rs:5:5
  |
5 | h = format!("{}, {}",h, w);
  |     ^^^^^^^^^^^^^^^^^^^^^^ expected &str, found struct `std::string::String`
  |
  = note: expected type `&str`
             found type `std::string::String`

For concat! I got his error:

error: expected a literal
 --> src/main.rs:6:12
  |
6 | h= concat!(h, ", ", w);
  |            ^        ^
  |
  = note: only literals (like `"foo"`, `42` and `3.14`) can be passed to `concat!()`

The issue is that h is a str reference but format! returns a new owned String (as it has to allocate new memory). If instead h were a mutable owned String you could do this:

let mut h = "Hello".to_string();
let w = "World";
h = format!("{}, {}",h, w);

Otherwise you'd need to declare a new variable for the result of format!.

2 Likes