Here's some self-explanatory code that I would expect to work:
type some_t = i32;
struct SomeStruct {
pub some_tuple_vector: Vec<(some_t, some_t)>,
}
impl SomeStruct {
fn some_method(&mut self) {
for p in self.some_tuple_vector.iter_mut() {
match p {
(x, y) if x < 0 => self.some_tuple_vector.remove(p),
(x, y) => p = (x, y - 1),
}
}
}
}
fn main() {}
However, I get errors on both lines that attempt to match and destructure the tuple:
error[E0308]: mismatched types
--> src/main.rs:12:17
|
12 | (x, y) if x < 0 => self.some_tuple_vector.remove(p),
| ^^^^^^ expected mutable reference, found tuple
|
= note: expected type `&mut (i32, i32)`
found type `(_, _)`
I don't understand it; isn't the type &mut (i32,i32)
a tuple itself?
I've realized that I can rewrite this code to be more elegant:
self.some_tuple_vector = self.some_tuple_vector
.iter()
.map(|(x, y)| (x - 1, y))
.filter(|(x, y)| x > 0);
But I get the same error:
error[E0308]: mismatched types
--> src/main.rs:12:19
|
12 | .map(|(x, y)| (x - 1, y))
| ^^^^^^ expected &(i32, i32), found tuple
|
= note: expected type `&(i32, i32)`
found type `(_, _)`
I don't quite understand it. Isn't the type
&mut (i32, i32)
a tuple itself?
No, it is a mutable reference to a tuple.
You also can't remove elements from a vector while iterating over it as this could lead to dangling pointers. remove
also removes an element at index. You'll have to do things differently:
type some_t = i32;
struct SomeStruct {
pub some_tuple_vector: Vec<(some_t, some_t)>,
}
impl SomeStruct {
fn some_method(&mut self) {
self.some_tuple_vector.retain(|tuple| tuple.0 >= 0);
for tuple in &mut self.some_tuple_vector {
tuple.1 -= 1;
}
}
}
fn main() {}
This could also be done in a loop
in one pass, but this is probably good enough.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments