Open zzz6519003 opened 1 year ago
hint
Hint 1: i
is each element from the Vec as they are being iterated. Can you try
multiplying this?
Hint 2: For the first function, there's a way to directly access the numbers stored in the Vec, using the * dereference operator. You can both access and write to the number that way.
After you've completed both functions, decide for yourself which approach you like better. What do you think is the more commonly used pattern under Rust developers?
second question:
hint
So, vec0
is passed into the fill_vec
function as an argument. 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.
Variables that are moved into a function (or block scope) and aren't explicitly
returned get "dropped" at the end of that function. This is also what happens here.
There's a few ways to fix this, try them all if you want:
vec0
and pass that
to fill_vec
instead.fill_vec
borrow its argument instead of taking ownership of it,
and then copy the data within the function in order to return an owned
Vec<i32>
fill_vec
mutably borrow a reference to its argument (which will need to be
mutable), modify it directly, then not return anything. Then you can get rid
of vec1
entirely -- note that this will change what gets printed by the
first println!