【问题标题】:Is it possible to have a closure in a structure with generic arguments and return type?是否可以在具有泛型参数和返回类型的结构中使用闭包?
【发布时间】:2020-07-06 04:01:13
【问题描述】:

是否可以用泛型参数和返回类型替换下面的闭包?

struct HMHolder<T>
where
    T: Fn(u32) -> u32,
{
    calculation: T,
    value: HashMap<String, i32>,
}

例如,我可以在该结构中创建Fn&lt;U, V&gt;(x: U) -&gt; V 并创建构造函数吗?

【问题讨论】:

  • 当你用更多的泛型替换具体类型时会发生什么?
  • 看来Unused type parameter on closure argument 的答案可能会回答您的问题。如果没有,请edit您的问题解释差异。否则,我们可以将此问题标记为已回答。
  • @Shepmaster,谢谢。正在寻找这个。不确定语法。谢谢。

标签: generics rust closures


【解决方案1】:

可能是这样(为其他未使用的类型参数指定幻像类型):

struct HMHolder<I, R, Calculation>
where
    Calculation: Fn(I) -> R,
{
    calculation: Calculation,
    value: std::collections::HashMap<String, i32>,
    marker: std::marker::PhantomData<(I, R)>,
}

【讨论】:

  • 如何从另一个函数调用它,例如: fn calculate_value(&mut self, arg: u32) -> HashMap { for i in 0..arg { let v = (self.计算)(i); self.value.insert(i, v); } self.value } ,它在 (self.calculation)(i) 中给出错误“不匹配的类型”。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-08
  • 1970-01-01
  • 2014-03-11
  • 1970-01-01
  • 2013-02-11
  • 1970-01-01
  • 2011-12-18
相关资源
最近更新 更多