use std::sync::atomic::{AtomicI32, Ordering::Relaxed};
pub struct Person {
id: i32,
name: String,
}
static NEXT_MALE_ID: AtomicI32 = AtomicI32::new(1);
static NEXT_FEMALE_ID: AtomicI32 = AtomicI32::new(-1);
impl Person {
pub fn new(name: String, is_male: bool) -> Self {
Person {
id: if is_male {
NEXT_MALE_ID.fetch_add(1, Relaxed)
} else {
NEXT_FEMALE_ID.fetch_sub(1, Relaxed)
},
name: name,
}
}
}
pub struct Spouse<'a, 'b> {
base: &'a Person,
engaged_to: Option<&'b Person>,
preferences: Vec<&'b Person>,
}
impl<'a, 'b> Spouse<'a, 'b> {
pub fn new(base: &'a Person, preferences: Vec<&'b Person>) -> Self {
Self {
base: base,
engaged_to: None,
preferences: preferences,
}
}
pub fn engage_to(mut self, spouse: Option<&'b Person>) {
self.engaged_to = spouse
}
pub fn prefers_more_than_current(self, spouse: &'a Person) -> Option<bool> {
match self.engaged_to {
None => Some(true),
Some(current) => {
for person in self.preferences {
if person.id == spouse.id {
return Some(true);
} else if person.id == current.id {
return Some(false);
}
}
None
}
}
}
}
struct Population<'a, 'b> {
males: Vec<Spouse<'a, 'b>>,
females: Vec<Spouse<'a, 'b>>,
}
pub fn engage<'h, 'w>(mut husband: &'h Spouse, mut wife: &'w Spouse) {
husband.engaged_to = Some(wife.base); // Illegal
wife.engaged_to = Some(husband.base); // Illegal
}
This is an emulation of the stable matching problem. Husbands and Wives have Person
bases. A Husband<'a, 'b>
has a base of &'a Person
and preference of Option<&'b Person>
. However when I try to engage a husband with a wife the compiler complains:
error[E0623]: lifetime mismatch
--> src/stable_matching.rs:66:26
|
65 | pub fn engage<'h, 'w>(mut husband: &'h Spouse, mut wife: &'w Spouse) {
| ------ ------ these two types are declared with different lifetimes...
66 | husband.engaged_to = Some(wife.base);
| ^^^^^^^^^^^^^^^ ...but data from `wife` flows into `husband` here
What's the syntax for specifying that the husband
parameter has a lifetime of <'h, 'w>
and wife
<'w, 'h>
?