Ownership is Rust’s central feature. The key selling point of Rust as a language is its memory safety. In Rust memory is managed through a system of ownership with a set of rules that the compiler checks at compile time. None of the ownership features slow down your program while it’s running.
Below are ownership rules,
* Each value in Rust has a variable that’s called its owner.
* There can only be one owner at a time.
* When the owner goes out of scope, the value will be dropped.
The ownership of value can be transferred by,
* Assigning value of one variable to another variable.
* Passing value to a function.
* Returning value from a function.
```
fn main() {
let s1 = String::from("hello");
let s2 = s1;
println!("{}, world!", s1);
}
/*
$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0382]: borrow of moved value: `s1`
--> src/main.rs:5:28
|
2 | let s1 = String::from("hello");
| -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait
3 | let s2 = s1;
| -- value moved here
4 |
5 | println!("{}, world!", s1);
| ^^ value borrowed here after move
error: aborting due to previous error
For more information about this error, try `rustc --explain E0382`.
error: could not compile `ownership`
To learn more, run the command again with --verbose.
*/
```