prepend a string to the beginning of another string in rust

To prepend a string to the beginning of another string in Rust, you can use concatenation with the + operator. Here's an example:

main.rs
fn main() {
    let mut s1 = String::from("world");
    let s2 = "hello ";
    s1 = s2.to_owned() + &s1;
    println!("{}", s1); // Output: "hello world"
}
156 chars
7 lines

In this example, we create two strings s1 and s2. We then use the to_owned() method to convert s2 to a String, and then use the + operator to concatenate s2 with a reference to s1.

Note that because Rust has ownership and borrowing rules, we must explicitly use a reference to s1 by prefixing it with the & symbol. We also use the mut keyword to make s1 mutable so we can modify it in place.

gistlibby LogSnag