mirror of
https://github.com/rust-lang/rustlings.git
synced 2024-12-25 15:10:26 +00:00
move_semantics2 solution
This commit is contained in:
parent
946c29679e
commit
68142aff7f
3 changed files with 35 additions and 14 deletions
|
@ -1,5 +1,3 @@
|
|||
// Make the test pass by finding a way to keep both Vecs separate!
|
||||
|
||||
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
|
||||
let mut vec = vec;
|
||||
|
||||
|
@ -16,13 +14,15 @@ fn main() {
|
|||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// TODO: Make both vectors `vec0` and `vec1` accessible at the same time to
|
||||
// fix the compiler error in the test.
|
||||
#[test]
|
||||
fn move_semantics2() {
|
||||
let vec0 = vec![22, 44, 66];
|
||||
|
||||
let vec1 = fill_vec(vec0);
|
||||
|
||||
assert_eq!(vec0, vec![22, 44, 66]);
|
||||
assert_eq!(vec1, vec![22, 44, 66, 88]);
|
||||
assert_eq!(vec0, [22, 44, 66]);
|
||||
assert_eq!(vec1, [22, 44, 66, 88]);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -352,16 +352,10 @@ When running this exercise for the first time, you'll notice an error about
|
|||
"borrow of moved value". In Rust, when an argument is passed to a function and
|
||||
it's not explicitly returned, you can't use the original variable anymore.
|
||||
We call this "moving" a variable. When we pass `vec0` into `fill_vec`, it's
|
||||
being "moved" into `vec1`, meaning we can't access `vec0` anymore after the
|
||||
fact.
|
||||
being "moved" into `vec1`, meaning we can't access `vec0` anymore.
|
||||
|
||||
Rust provides a couple of different ways to mitigate this issue, feel free to
|
||||
try them all:
|
||||
1. You could make another, separate version of the data that's in `vec0` and
|
||||
pass that to `fill_vec` instead.
|
||||
2. Make `fill_vec` borrow its argument instead of taking ownership of it,
|
||||
and then copy the data within the function (`vec.clone()`) in order to
|
||||
return an owned `Vec<i32>`.
|
||||
You could make another, separate version of the data that's in `vec0` and
|
||||
pass it to `fill_vec` instead.
|
||||
"""
|
||||
|
||||
[[exercises]]
|
||||
|
|
|
@ -1 +1,28 @@
|
|||
// Solutions will be available before the stable release. Thank you for testing the beta version 🥰
|
||||
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_semantics2() {
|
||||
let vec0 = vec![22, 44, 66];
|
||||
|
||||
// Cloning `vec0` so that the clone is moved into `fill_vec`, not `vec0`
|
||||
// itself.
|
||||
let vec1 = fill_vec(vec0.clone());
|
||||
|
||||
assert_eq!(vec0, [22, 44, 66]);
|
||||
assert_eq!(vec1, [22, 44, 66, 88]);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue