Clicking something into a vector depending on its last element

I would like to get the last element of the vector and use it to determine the next element to enter. Here is an example of how it does not work, but it shows what I'm trying to achieve:

let mut vector: Vec<i32> = Vec::new(); match vector.last() { Some(last_value) => vector.push(*last_value + 1), None => (), } 

The problem is that I cannot use push while the vector is also borrowed invariably. What would be a good way to do this?

+5
source share
1 answer

The result of vector.last() is Option<&i32> . A link in this value saves the borrowed vector. We need to get rid of all the links in the vector before we can click on it.

If your vector contains Copy capable values, copy the value from the vector to finish borrowing earlier.

 fn main () { let mut vector: Vec<i32> = Vec::new(); match vector.last() { Some(&last_value) => vector.push(last_value + 1), None => (), } } 

Here I used the template Some(&last_value) instead of Some(last_value) . This destroys the link and makes it copy. If you try this template with a type that Copy is not capable of, you will get a compiler error:

 <anon>:5:14: 5:25 error: cannot move out of borrowed content <anon>:5 Some(&last_value) => vector.push(last_value + "abc"), ^~~~~~~~~~~ 

If your vector does not contain Copy capable types, you might want to clone the value first:

 fn main () { let mut vector: Vec<String> = Vec::new(); match vector.last().map(|v| v.clone()) { Some(last_value) => vector.push(last_value + "abc"), None => (), } } 

Or you can convert the value differently so that the .map() call returns a value that is not taken from the vector.

 fn main () { let mut vector: Vec<String> = Vec::new(); // Push a string containing the length of the last element. match vector.last().map(|v| v.len().to_string()) { Some(new_value) => vector.push(new_value), None => (), } } 
+7
source

Source: https://habr.com/ru/post/1234569/


All Articles