Skip to main content

Rust_Data_Type_String

String Concatenation

  • String.push_str(&str);
  • String.push_str(&String);
  • operator + (String + &str)
  • format macro (String+ String) or (&str+ &str)

String + &str


fn main() {
let mut owned_string: String = "hello ".to_owned();
let borrowed_string: &str = "world";

owned_string.push_str(borrowed_string);
println!("{owned_string}");
}

String + String

fn main() {
let mut owned_string: String = "hello ".to_owned();
let another_owned_string: String = "world".to_owned();

owned_string.push_str(&another_owned_string);
println!("{owned_string}");
}

use + operator to combine String and &str

fn main() {
let owned_string: String = "hello ".to_owned();
let borrowed_string: &str = "world";

let new_owned_string = owned_string + borrowed_string;
println!("{new_owned_string}");
}

Concate 2 %str by format macro

fn main() {
let borrowed_string: &str = "hello ";
let another_borrowed_string: &str = "world";

let together = format!("{borrowed_string}{another_borrowed_string}");
println!("{}", together);
}

Concate 2String by format macro

fn main() {
let owned_string: String = "hello ".to_owned();
let another_owned_string: String = "world".to_owned();

let together = format!("{owned_string}{another_owned_string}");
println!("{}", together);
}

use + operator to combine String and &str

fn main() {
let owned_string: String = "hello ".to_owned();
let borrowed_string: &str = "world";

let together = owned_string.clone() + borrowed_string;
println!("{together}");
}