Does this mean that it's impossible to use mutable methods on any of the Iterator's methods (find
, filter
, etc.)?
In the methods that receive a parameter of type F: Fn*(&Self::Item)
, yes. One cannot call a method that expects a mutable reference (&mut
) on a reference (&
). For example:
let mut x = vec![10];
// (&x)[0] = 20; // not ok
(&mut x)[0] = 20; // ok
//(& (&x))[0] = 20; // not ok
//(& (&mut x))[0] = 20; // not ok
(&mut (&mut x))[0] = 20; // ok
Note that this rule also applies to auto deref.
Some methods of Iterator
receive a parameter of type F: Fn*(Self::Item)
, like map
, filter_map
, etc. These methods allow functions that mutate the item.
One interesting question is: Why do some methods expect Fn*(&Self::Item)
and others Fn*(Self::item)
?
The methods that will need to use the item, like filter
(that will return the item if the filter function returns true
), cannot pass Self::Item
as parameter to the function, because doing that means give the ownership of the item to the function. For this reason, methods like filter
pass &Self::Item
, so they can use the item later.
On the other hand, methods like map
and filter_map
do not need the item after they are used as arguments (the items are being mapped after all), so they pass the item as Self::Item
.
In general, it is possible to use filter_map
to replace the use of filter
in cases that the items need to be mutated. In your case, you can do this:
extern crate libusb;
fn main() {
let mut context = libusb::Context::new().expect("context creation");
let mut filtered: Vec<_> = context.devices()
.expect("devices list")
.iter()
.filter_map(|mut r| {
if let Ok(d) = r.device_descriptor() {
if d.vendor_id() == 7531 {
return Some(r);
}
}
None
})
.collect();
for d in &mut filtered {
// same as: for d in filtered.iter_mut()
println!("{:?}", d.device_descriptor());
}
}
The filter_map
filters out None
values and produces the wrapped values in Some
s.