Every time I think I've got idiomatic Rust a little bit figured out, it defeats me again. In this case, I've got a struct State
which contains, among other things, a Vec<Option<Dude>>
called ods
, where Dude
is a struct that looks like this:
pub struct Dude {
pub capacity: i32,
pub status: DudeStatus,
}
What I would LIKE to do is define a function/method on State
that iterates through ods
. If a Dude
is present in the given index (that is, if ods[i] == Some(Dude)
), decrement his capacity by one, and if that causes capacity==0
, remove the Dude
from ods
. Unfortunately, I seem to be running into type inference and/or ownership issues. Here's my attempt:
fn tick(&mut self) {
for d in &self.ods {
match d {
Some(du) => {
du.capacity -= 1;
if du.capacity == 0 {
d.take();
}
}
None => {}
};
}
}
However, this gives 3 compilation errors:
src/state.rs:40:18: 40:26 error: mismatched types:
expected `&std::option::Option<dude::Dude>`,
found `std::option::Option<_>`
(expected &-ptr,
found enum `std::option::Option`) [E0308]
src/state.rs:40 Some(du) => {
^~~~~~~~
src/state.rs:46:18: 46:22 error: mismatched types:
expected `&std::option::Option<dude::Dude>`,
found `std::option::Option<_>`
(expected &-ptr,
found enum `std::option::Option`) [E0308]
src/state.rs:46 None => {}
src/state.rs:41:22: 41:32 error: the type of this value must be known in this context
src/state.rs:41 du.capacity -=1;
The third error is easy enough to understand conceptually, but I'm not sure where I should be annotating the type. Type ascription is currently an experimental feature so I can't use match d: Option<Dude>
which, to me, is the most intuitive. Additionally the other two errors suggest I have a borrow/reference error. What am I doing wrong?