String slice in Rust

str String to_owned

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