我一整天都在研究以下代码,(这是围栏)
/// The rule that moves state from one to another.
///
/// `S` - the type parameter of state.
///
/// `T` - the type parameter of input symbol.
#[deriving(PartialEq, Eq, Hash)]
pub struct Rule<S, T> {
pub state: S,
pub symbol: Option<T>,
pub next_state: S
}
impl<S: PartialEq, T: PartialEq> Rule<S, T> {
/// determine whether the rule applies to the given state and symbol
pub fn apply_to(&self, state: &S, symbol: &Option<T>) -> bool {
self.state == *state && self.symbol == *symbol
}
}
/// The transition relation in NFA,
/// containing all the rules needed by the NFA.
pub struct NFATransitions<S, T> {
pub rules: HashSet<Rule<S, T>>
}
impl<S: Eq + Hash + Clone, T: Eq + Hash> NFATransitions<S, T> {
pub fn next_states(&self, states: &HashSet<S>, symbol: &Option<T>) -> HashSet<S> {
states.iter().flat_map(|state| {
// error goes here: borrowed value does not live long enough
self.next_states_for(state, symbol).iter().map(|s| s.clone())
}).collect()
// Howover, the following code which have the same behavior can compile
// let mut result = HashSet::new();
// for state in states.iter() {
// result.extend(self.next_states_for(state, symbol).iter().map(|s| s.clone()));
// }
//
// result
}
/// get the next state for the given state and symbol
fn next_states_for(&self, state: &S, symbol: &Option<T>) -> HashSet<S> {
self.rules.iter().filter_map(|rule| {
if rule.apply_to(state, symbol) { Some(rule.next_state.clone()) } else { None }
}).collect()
}
}
Run Code Online (Sandbox Code Playgroud)
代码只是用于nfa转换规则的hashset的包装器.(这不是我所关心的)
这flat_map是我得到编译错误的地方.这对我来说似乎很奇怪,因为我认为具有相同行为的注释行flat_map可以很好地完成.
我无法弄清楚error: borrowed value does not live long enough错误是如何产生的.
有任何想法吗 ?
这里的问题是iter(),这与 的结果的生命周期相关next_states_for(),并且是&- 指针的迭代器。
由于next_states_for()已经为您克隆了一些东西,into_iter()所以这就是您想要的,这会将项目从集合中移出。
pub fn next_states(&self, states: &HashSet<S>, symbol: &Option<T>) -> HashSet<S> {
states.iter().flat_map(|state| {
// error goes here: borrowed value does not live long enough
self.next_states_for(state, symbol).into_iter()
}).collect()
}
Run Code Online (Sandbox Code Playgroud)
闭包通过引用捕获,这就是它与 for 循环不同的原因。
| 归档时间: |
|
| 查看次数: |
2526 次 |
| 最近记录: |