如何在Rust中表达空的特质约束?

huangapple go评论58阅读模式
英文:

How to express vacuous trait bound in rust?

问题

我想让K和V隐式地具有使HashMap<K,V>有效的任何约束。是否有比Default更能传达这一意图的特质?类似于HashMap<K,V>: True 的东西?

英文:

Suppose I want to write a HashMap wrapper. My attempt:

struct Wrapper&lt;K,V&gt; where HashMap&lt;K,V&gt;: Default{
   value: HashMap&lt;K,V&gt;
}

I want K,V to implicitly have whatever bounds that make HashMap<K,V> valid. Is there a trait that is better than Default that better communicates this intention? Something like HashMap<K,V>: True ?

答案1

得分: 5

HashMap 在类型上对任何键/值类型都是有效的。您可以使用任何类型调用 HashMap::new

显然,这并不是非常有用,但没有类型级别的有用度量,因此无法绕过复制特质边界。几乎所有 HashMap 的方法都在 这个实现块 中,因此您只需复制该块的边界。

where K: Eq + Hash

如果可能的话,您应该只在需要它的 impl 块上放置它,而不是在结构体上。查看这个问题以获得解释。 您可能还需要在每个方法上放置边界,就像 HashMap 所做的那样。

where
    K: Borrow<Q>,
    Q: Hash + Eq + ?Sized,
英文:

HashMap is valid, type-wise, for any key/value types. You can call HashMap::new with any types.

Obviously this isn't very useful, but there's no type-level usefulness measure, so you can't work around copying the trait bounds. Nearly all of HashMap's methods are in this impl block, so you can just copy the bounds of that one.

where K: Eq + Hash

You should put this only on the impl block that requires it and not on the struct, if possible. See this question for an explanation. You may also need to put bounds on each method, like what HashMap does.

where
    K: Borrow&lt;Q&gt;,
    Q: Hash + Eq + ?Sized,

huangapple
  • 本文由 发表于 2023年5月8日 02:33:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76195651.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定