Strings and memory (re)allocation (video)

push push_str as_ptr :p

examples/strings-and-memory-reallocation/src/main.rs

macro_rules! prt {
    ($var:expr) => {
        println!(
            "{:2} {:2} {:p} {:15?} '{}'",
            $var.len(),
            $var.capacity(),
            &$var,
            $var.as_ptr(),
            $var
        );
    };
}
fn main() {
    let mut text = String::new();
    prt!(text);
    text.push('a');
    prt!(text);

    let name = String::from("foobar");
    prt!(name);

    text.push('b');
    prt!(text);
    text.push_str("123456");
    prt!(text);

    text.push('x');
    prt!(text);

    text.push_str("123456789123143274368741");
    prt!(text);
}

 0  0 0x7fff828f9e70             0x1 ''
 1  8 0x7fff828f9e70  0x5ed486472ba0 'a'
 6  6 0x7fff828fa5b8  0x5ed486472bc0 'foobar'
 2  8 0x7fff828f9e70  0x5ed486472ba0 'ab'
 8  8 0x7fff828f9e70  0x5ed486472ba0 'ab123456'
 9 16 0x7fff828f9e70  0x5ed486472ba0 'ab123456x'
33 33 0x7fff828f9e70  0x5ed486472be0 'ab123456x123456789123143274368741'

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