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

标签 rust

我一整天都在编写以下代码,(here 是围栏)

/// 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 错误是如何产生的。

有什么想法吗?

最佳答案

这里的问题是 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 循环不同的原因。

关于rust - `flat_map` 如何影响我的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26240489/

相关文章:

rust - 是否可以在 Rust 的 docopt 中默认将 bool 选项设置为 'true'?

tcp - BufWriter::write() 不会将字节写入 TcpStream

multithreading - 向量中函数的线程调用

rust - 闭包内容器对象的生命周期推理

rust - 无法在 Rust 中将结构编码为 JSON

Rustc 仅在分配溢出的值时发出警告

rust - 如何使用前缀键搜索获得排序的键值映射?

rust - "Cannot move out of dereference ` & `-pointer"带向量

rust - 如何从给定 block 的访问者那里获得 lint 级别?

rust - Once_cell的异步版本,或者避免错误的方法[E0744] : `.await` is not allowed in a `static` ?