FaultierSP
FaultierSP

Reputation: 95

Is there a better way to chain strings together than multiple push_str() calls?

I would like to chain strings together. This is my code:

let mut string_to_send = String::new();
string_to_send.push_str("<hi,");
string_to_send.push_str(&some_int.to_string());
string_to_send.push_str(",");
string_to_send.push_str(&another_int.to_string());
string_to_send.push_str(">");

Something tells me there is a nicer way to do it, but I just don't see it.

Upvotes: 5

Views: 459

Answers (3)

pigeonhands
pigeonhands

Reputation: 3424

You can use concat for this

let string_to_send = [
    "<hi",
    &10.to_string(),
    ",",
    &11.to_string(),
    ">"
].concat();

Upvotes: 1

Kaplan
Kaplan

Reputation: 3738

Concatenation with the + operator:

let string_to_send =
    "<hi,".to_string() + &some_int.to_string() + "," + &another_int.to_string() + ">";

The converted &String values of the int's become coerced into &str arguments before the call of the + operator.

Upvotes: 0

Lee
Lee

Reputation: 144136

You can use format!:

let mut string_to_send = format!("<hi,{},{}>", some_int, another_int);

As Holloway points out in the comments, since Rust 1.58 you can capture identifiers in format strings:

let mut string_to_send = format!("<hi,{some_int},{another_int}>");

Upvotes: 9

Related Questions