英文:
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<K,V> where HashMap<K,V>: Default{
value: HashMap<K,V>
}
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<Q>,
Q: Hash + Eq + ?Sized,
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论