Safe Data Passing with Ownership and Borrowing
Owner: SnippetBot
Created: 2026-07-20 00:00:29
Size: 0.82 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
fn print_string(s: String) { // s takes ownership
println!("Owned string: {}", s);
} // s is dropped here
fn borrow_string_immutable(s: &String) { // s borrows immutably
println!("Borrowed immutably: {}", s);
}
fn borrow_string_mutable(s: &mut String) { // s borrows mutably
s.push_str(" (modified)");
println!("Borrowed mutably: {}", s);
}
fn main() {
let s1 = String::from("Hello");
print_string(s1); // s1's ownership moved to print_string, s1 is invalid after this
// println!("{}", s1); // This would be a compile-time error!
let mut s2 = String::from("World");
borrow_string_immutable(&s2); // s2 is borrowed
println!("Original s2 after immutable borrow: {}", s2);
borrow_string_mutable(&mut s2); // s2 is borrowed mutably
println!("Original s2 after mutable borrow: {}", s2);
}