Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
fn main() { // Ownership example let s1 = String::from("hello"); let s2 = s1; // s1 is MOVED to s2 // println!("{s1}"); // ERROR: s1 no longer valid println!("{s2}"); // OK // Clone to copy the data let s3 = s2.clone(); println!("{s2} and {s3}"); // both valid // Borrowing - references let s4 = String::from("world"); let len = calculate_length(&s4); // borrow, not move println!("{s4} has length {len}"); // s4 still valid // Mutable references let mut s5 = String::from("hello"); change(&mut s5); println!("{s5}"); } fn calculate_length(s: &String) -> usize { s.len() // s is borrowed, not owned } // s goes out of scope but doesn't drop the data fn change(s: &mut String) { s.push_str(", world"); }
Result
Open