Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Rust clone a String

  • clone

  • In some cases what we will want is to copy the content of the variable.

  • For this we can use the clone method.

macro_rules! prt {
    ($var:expr) => {
        println!(
            "{:2} {:2} {:p} {:15?} '{}'",
            $var.len(),
            $var.capacity(),
            &$var,
            $var.as_ptr(),
            $var
        );
    };
}

fn main() {
    let x = String::from("Foo Bar");
    prt!(x);
    let y = x.clone();
    prt!(x);
    prt!(y);
}
 7  7 0x7ffdaf695048  0x648f6a2b5b80 'Foo Bar'
 7  7 0x7ffdaf695048  0x648f6a2b5b80 'Foo Bar'
 7  7 0x7ffdaf695448  0x648f6a2b5ba0 'Foo Bar'