`flat_map` 如何影响我的代码?

6

我已经花了一整天的时间在以下代码上进行工作,(这里是playpen)

/// 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()
  }
}

这段代码只是一个哈希集合的包装器,用于nfa转换规则。(这不是我关心的)

flat_map 是我得到编译错误的地方。 对我来说很奇怪,因为我认为有着与 flat_map 相同行为的被注释掉的代码行可以正常运行。

我无法想象出 error: borrowed value does not live long enough 错误是如何产生的。

任何想法?


我猜测闭包的结果寿命太短,因为next_states_for的结果是临时的。 - user395760
1
你能提供一个带有Rule源代码/实现的playpen链接吗? - snf
@delnan,那么你对此有什么线索吗?毕竟,这似乎是一个常见的用法。 - Windor C
1个回答

3
这里的问题在于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()
  }

闭包通过引用捕获变量,这就是为什么它与for循环不同的原因。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接