Possible link to an element using Find in Rust

How can I get a mutable link to an element found in a vector?

I tried the following, which works if I do not change the iterator with .iter():

fn main() {
    let mut vec = vec![1, 2, 3, 4];
    let mut wrong = -1;

    let working = match vec.iter().find(|&c| *c == 2) {
        Some(c) => c,
        None => &wrong
    };

    println!("Result: {}", working);
}

But when I try to get a mutable link using a mutable iterator .iter_mut(),

fn main() {
    let mut vec = vec![1, 2, 3, 4];
    let mut wrong = -1;

    let mut error = match vec.iter_mut().find(|&c| *c == 2) {
        Some(c) => c,
        None => &mut wrong
    };

    println!("Result: {}", error);
}

I get the following error:

error[E0507]: cannot move out of borrowed content
 --> src/main.rs:5:48
  |
5 |     let mut error = match vec.iter_mut().find(|&c| *c == 2) {
  |                                                ^-
  |                                                ||
  |                                                |hint: to prevent move, use `ref c` or `ref mut c`
  |                                                cannot move out of borrowed content

I also tried to make the type in closure mutable with |&mut c|, but this gives the following error:

error[E0308]: mismatched types
 --> src/main.rs:5:48
  |
5 |     let mut error = match vec.iter_mut().find(|&mut c| *c == 2) {
  |                                                ^^^^^^ types differ in mutability
  |
  = note: expected type `&&mut {integer}`
             found type `&mut _`
  = help: did you mean `mut c: &&&mut {integer}`?
+4
source share
1 answer

Rust .find &Self::Item, .iter_mut(), &mut T. , , find, &&mut T. typecheck,

vec.iter_mut().find(|&&mut c| c == 2)

vec.iter_mut().find(|c| **c == 2)

.

, , , &c c &mut T, Rust - , . , .

+6

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


All Articles