String slice in Rust

str String to_owned

When we create a variable like let text = "Some text"; this strings is included in the binary compiled by rustc. That means in the first example the variable text is itself a slice in the whole binary. We can still refer to parts of it (slices of it). We had to make the variable mutable so we can change it.

In the second example we use the String::from function to create a string and allocate memory for it on the heap. That means we can actully change the string (by pushing some data on it) but what we see here is that we can access parts of it by referring to thos parts as references.

examples/string-slice/src/main.rs

fn main() {
    as_str();
    println!("---");
    as_string();
}

fn as_str() {
    let mut text = "The black cat climbed the green tree";
    println!("{}", text);
    println!("{}", &text[4..9]);
    println!("{}", &text[4..31]);

    {
        let text = &text[4..31];
        println!("{}", text);
    }

    println!("{}", text);

    {
        text = &text[4..25];
        println!("{}", text);
    }
    println!("{}", text);
}

fn as_string() {
    let mut text = String::from("The black cat climbed the green tree");
    println!("{}", text);
    println!("{}", &text[4..9]);
    println!("{}", &text[4..31]);

    {
        let text = &text[4..31]; // here text is going to be &str till the end of the block
        println!("{}", text);
    }

    println!("{}", text);

    {
        text = text[4..25].to_owned();
        println!("{}", text);
    }
    println!("{}", text);
}

examples/string-slice/out.txt

The black cat climbed the green tree
black
black cat climbed the green
black cat climbed the green
The black cat climbed the green tree
black cat climbed the
black cat climbed the
---
The black cat climbed the green tree
black
black cat climbed the green
black cat climbed the green
The black cat climbed the green tree
black cat climbed the
black cat climbed the

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo