Lesson 6 of 20
Ownership
Ownership
Ownership is Rust's most distinctive feature. It enables memory safety without a garbage collector.
The Three Rules
- Each value in Rust has an owner.
- There can only be one owner at a time.
- When the owner goes out of scope, the value is dropped (memory freed).
Move Semantics
When you assign a heap-allocated value to another variable, ownership moves:
let s1 = String::from("hello");
let s2 = s1; // s1 is MOVED into s2
// println!("{}", s1); // ERROR: s1 was moved
println!("{}", s2); // OK
Copy Types
Types that live entirely on the stack implement the Copy trait and are copied instead of moved:
let x = 5;
let y = x; // x is COPIED, not moved
println!("{}", x); // OK — x still valid
Integers, floats, booleans, and chars are Copy. String is not.
Clone
To explicitly copy heap data, use .clone():
let s1 = String::from("hello");
let s2 = s1.clone(); // deep copy
println!("{} {}", s1, s2); // both valid
Ownership and Functions
Passing a value to a function moves or copies it, just like assignment:
fn take_ownership(s: String) {
println!("{}", s);
} // s is dropped here
fn makes_copy(x: i32) {
println!("{}", x);
} // x is copied, original still valid
Your Task
Implement three functions:
make_greeting(name: &str) -> String— returns a greeting like "Hello, Alice!" usingformat!.string_length(s: String) -> (String, usize)— takes ownership of a string, returns it together with its length.repeat_string(s: &str, n: usize) -> String— returns the string repeated n times.
Rust (Miri) loading...
Loading...
Click "Run" to execute your code.