Об'єднання рядків

Rust:
Об'єднання рядків

How to (Як це робити)

Here’s how you glue strings together in Rust:

fn main() {
    let hello = "Вітаю".to_string();
    let world = "Світ";
    let exclamation = "!";
    
    // Using the + operator
    let greeting = hello + " " + world + exclamation;
    println!("{}", greeting);  // Вітаю Світ!
    
    // Using format! macro
    let formatted_greeting = format!("{} {}{}", "Вітаю", "Світ", "!");
    println!("{}", formatted_greeting);  // Вітаю Світ!
}

Common ways to combine strings in Rust include using the + operator or the format! macro. Note the difference in borrow-checker requirements: with +, hello needs to be a String (not a &str) because the operator takes ownership of hello.

Deep Dive (Поглиблений огляд)

Concatenating strings is as old as programming itself; it’s been in use since the early days to allow programs to communicate complex messages. In Rust, string concatenation respects ownership and borrowing rules, which is why String and &str (string slices) have different behaviors. Alternatives to concatenation also exist, like joining strings in a vector with join() method or building up a string with a StringWriter.

// Using join() method on a vector of strings
let words = vec!["Вітаю", "Світ", "!"];
let joined = words.join(" ");
println!("{}", joined); // Вітаю Світ!

// Using push_str to build up a string
let mut message = String::from("Вітаю");
message.push_str(" Світ");
message.push_str("!");
println!("{}", message); // Вітаю Світ!

See Also (Дивіться також)

To dig deeper into Rust strings:

This should get you started. Щасливого кодування! (Happy coding!)