profileRyan KesPGP keyI build stuffEmailGithubTwitterLast.fmMastodonMatrix

Rust Strings

Description

The String type, which is provided by Rust’s standard library rather than coded into the core language, is a growable, mutable, owned, UTF-8 encoded string type. When Rustaceans refer to “strings” in Rust, they usually mean the String and the string slice &str types, not just one of those types. Although this section is largely about String, both types are used heavily in Rust’s standard library, and both String and string slices are UTF-8 encoded.

Creating a New String

Many Vector operations are also available for Strings.

fn main() {
    let mut s = String::new();
}

to~string~

To generate a String with initial data we can use the to~string~ method:

fn main() {
    let data = "initial contents";

    let s = data.to_string();

    // the method also works on a literal directly:
    let s = "initial contents".to_string();
}

String::from

The same can be accomplished with String::from:

fn main() {
    let s = String::from("initial contents");
}

Updating a String

push~str~

fn main() {
    let mut s = String::from("foo");
    s.push_str("bar");

    println!("s is {}", s)
}

push

push adds a single character to a string:

fn main() {
    let mut s = String::from("lo");
    s.push('l');

    println!("s is {}", s)
}

Concatentation

fn main() {
    let s1 = String::from("Hello, ");
    let s2 = String::from("world!");
    let s3 = s1 + &s2; // note s1 has been moved here and can no longer be used

    println!("s3 is {}", s3)
}

Concatenate multiple strings

With +

fn main() {
    let s1 = String::from("tic");
    let s2 = String::from("tac");
    let s3 = String::from("toe");

    let s = s1 + "-" + &s2 + "-" + &s3;

    println!("s is {}", s)
}

With format!

fn main() {
    let s1 = String::from("tic");
    let s2 = String::from("tac");
    let s3 = String::from("toe");

    let s = format!("{}-{}-{}", s1, s2, s3);

    println!("s is {}", s)
}

Iteration

Chars

#![allow(unused)]
fn main() {
    for c in "नमस्ते".chars() {
        println!("{}", c);
    }
}

Bytes

#![allow(unused)]
fn main() {
    for b in "नमस्ते".bytes() {
        println!("{}", b);
    }
}