struct AttributeState<'a>{
keys: HashSet<&'a str>,
values: HashSet<&'a str>,
header_base_score: f64,
value_base_score: f64,
}
impl<'a> AttributeState<'a>{
pub(crate) fn contain_key(&self, entity: &str) -> bool{
self.keys.contains(entity)
}
pub(crate) fn contains_value(&self, entity: &str) -> bool{
self.values.contains(entity)
}
pub(crate) fn add_header(&'a mut self, entity: &'a str){
self.keys.insert(entity);
}
pub(crate) fn add_value(&'a mut self, entity: &'a str){
self.values.insert(entity);
}
}
pub(crate) struct TableScoring {
name: String,
primary_key: String,
}
impl TableScoring {
fn scoring(&self, candidate: &Vec<Token>) -> f64{
let mut primary_mask = 0x0u8;
// let mut attribute_mask = 0x0u32;
let mut attribute_state = AttributeState::new(1.0, 1.2);
let mut cell_state = RefCell::new(attribute_state);
let mut score = 0.0;
for token in candidate{
if token.is_primary(&self.primary_key){
score += self.primary_scoring(token, &mut primary_mask);
}else {
let mut mut_state = cell_state.borrow_mut();
score += self.attribute_scoring(token, &mut mut_state);
}
}
score
}
fn primary_scoring(&self, token: &Token, mask: &mut u8) -> f64{
unimplemented!()
}
fn attribute_scoring<'a>(&self, token: &'a Token, state: &'a mut RefMut<AttributeState<'a>>) -> f64
{
// do something, 将token.entity添加到state.keys和values
// 逻辑上来说,token的生命周期应该更长,才能将token.entity的引用添加到state
// 编译器却要求state的生命周期应该比token更长 attribute_scoring<'a, 'b: 'a>(&self, token: &'a Token, state: &'b mut RefMut<AttributeState<'a>>)
unimplemented!()
}
}
// 对于return a或b的引用,return value的生命周期应该更短
// Here, Rust infers a lifetime that is as short as possible.
// The two references are then coerced to that lifetime.
fn multiply<'a>(first: &'a i32, second: &'a i32) -> i32 {
first * second
}
// `<'a: 'b, 'b>` reads as lifetime `'a` is at least as long as `'b`.
// Here, we take in an `&'a i32` and return a `&'b i32` as a result of coercion.
fn choose_first<'a: 'b, 'b>(first: &'a i32, _: &'b i32) -> &'b i32 {
first
}
fn main() {
let first = 2; // Longer lifetime
{
let second = 3; // Shorter lifetime
println!("The product is {}", multiply(&first, &second));
println!("{} is the first", choose_first(&first, &second));
};
}
但是对于改变可变形参的情况,看编译器的报错,mut_state是局部变量,无法满足借用检查,似乎只能将state中的Keys和Values的Item改成String才可以。为什么?