Ownership

Learn how Rust manages to be a memory-safe language without a garbage collector.

This might be the most challenging part of Rust. However, once we get familiar with it, it’ll become easier to use.

Ownership is the methodology we use to handle memory safely without a garbage collector.

Move semantic

Most languages copy the value when we access it from another place, but Rust moves the value or transfers ownership of it. This way, we can’t access it from the original variable.

Press + to interact
fn main() {
let string = "Hello World!".to_string();
let _new_place = string;
println!("this will generates an error: {}", string);
}

The above code will return an error stating that the variable was moved and can’t be used after the move.

There are two ways to solve this error:

  • Cloning
  • Reference

Cloning

The first solution is cloning the variable. We need to be aware that this represents a cost.

The cost of cloning is ...