Move Semantics
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 will be dropped.
When assigning a value to another variable or passing it to a function, ownership is transferred (moved).
Borrowing lets you access a value without transferring ownership, using references (
&).You can have only one mutable reference or any number of immutable references at a time.
References:
move_semantics1.rs
// TODO: Fix the compiler error in this function.
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
let mut vec = vec;
vec.push(88);
vec
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn move_semantics1() {
let vec0 = vec![22, 44, 66];
let vec1 = fill_vec(vec0);
assert_eq!(vec1, vec![22, 44, 66, 88]);
}
}In this exercise the function
fill_vectried to changevecvariables.But it got compile error because
vecis not mutable.When passing
vec0into functionfill_vecit also transfer or move the ownership frommainfunction tofill_vecfunction.So
fill_vecas the owner can do anything with it including change the mutability.Then we can easily add mutable in here
let mut vec = vec;to fix the code.And that makes
vecis mutable and we can push value into it.
move_semantics2.rs
In this exercise the task is to make both
vec0andvec1accessible at the same time.If we pass
vec0to functionfill_vecit will transfer or move the ownership.That make the
vec0variable invalidated and we got error:So instead of passing
vec0we pass a clone ofvec0.That makes both
vec0andvec1valid.
move_semantics3.rs
This exercise is similar with
move_semantics1.rs.But instead of changing the mutability by redeclare variables with
mutwe do it inside the function parameters.
move_semantics4.rs
You can have only one mutable reference or any number of immutable references at a time.
So the original code have compile error because of
xhave more than one mutable reference.By simply moving
y.push(42);abovelet z = &mut x;we can fix it.Because
yalready done with the push soxis free and can be borrowed byzin the next step.
move_semantics5.rs
If we look at the comment the function
string_uppercaseit shouldn't take ownership but the original code does it.So we just need to add reference
data: &Stringto the parameter and pass&datawhen callingget_char.That makes it borrow instead of move.
For
string_uppercaseremove the reference from data parameters because we want to move the ownership to it and remove the reference too when calling it.
Last updated