我有一个特征方法,它通过线性扫描集合中的元素来查找对集合中元素的引用。
我希望能够为 Vec<Tag>
实现一次和&'a [Tag]
(理想情况下也支持其他可迭代数据结构)。
在下面的代码中, TagFinder
的实例Vec<Tag>
的实现方式相同和&'a [Tag]
,但我找不到一种通用的方式来表达这一点。可能吗?
这个other question似乎相关,但我在这里有一个额外的间接级别,因为我处理的是“iterables”而不是迭代器。
与此相关,如果有像 IntoIterator
这样的特征,似乎会很方便。暴露了引用的迭代器(即 Vec<T>
和 &[T]
都会迭代 &T
,而不是 Vec<T>
暴露拥有的迭代器)。我不确定为什么这样的事情不存在。
struct Tag {
key: String,
value: String,
}
trait TagFinder {
fn find_tag(&self, key: &str) -> Option<&str>;
}
impl<'a> TagFinder for &'a [Tag] {
fn find_tag(&self, key: &str) -> Option<&str> {
find_tag(self.into_iter(), key)
}
}
impl TagFinder for Vec<Tag> {
fn find_tag(&self, key: &str) -> Option<&str> {
find_tag(self.into_iter(), key)
}
}
fn find_tag<'a, I>(tags: I, key: &str) -> Option<&'a str>
where
I: Iterator<Item = &'a Tag>,
{
tags.filter_map(|tag| match tag {
&Tag {
key: ref k,
value: ref v,
} if k == key =>
{
Some(v as &str)
}
_ => None,
}).next()
}
fn main() {
let v = vec![
Tag {
key: "a".to_owned(),
value: "1".to_owned(),
},
Tag {
key: "b".to_owned(),
value: "2".to_owned(),
},
];
let s: &[Tag] = &v;
assert!(v.find_tag("b") == Some("2"));
assert!(s.find_tag("b") == Some("2"));
}
编辑
经过一番尝试后,我得出了以下结论。它有效,但我不太清楚为什么它有效。
该特征现在消耗
self
,这根本不是可取的,除非IntoIterator<Item = &'a Tag>
的唯一实现者似乎是借用类型,所以self
被破坏的只是一个引用。我有点警惕,因为没有什么(除了约定)可以阻止某人为像Vec
这样的拥有类型实现这一点。 .将生命周期参数从方法(已删除)移至特征很奇怪。我发现很难理解返回值如何最终具有合理的生命周期。
为什么
v.find_tag(...)
工作?这里的接收者是Vec
不是引用。 Rust 如何将其转换为引用?
谢谢。 :)
trait TagFinder<'a> {
fn find_tag(self, key: &str) -> Option<&'a str>;
}
impl<'a, T> TagFinder<'a> for T
where
T: IntoIterator<Item = &'a Tag>,
{
fn find_tag(self, key: &str) -> Option<&'a str> {
find_tag(self.into_iter(), key)
}
}
最佳答案
How to implement trait once for all iterables of
&T
与您指定的差不多:
trait Foo {}
impl<'a, T: 'a, I> Foo for I
where
I: Iterator<Item = &'a T>,
{
}
您可以替换IntoIterator
对于 Iterator
如果你愿意的话。
对于您的具体情况:
trait TagFinder<'a> {
fn find_tag(self, key: &str) -> Option<&'a str>;
}
impl<'a, I> TagFinder<'a> for I
where
I: IntoIterator<Item = &'a Tag>,
{
fn find_tag(self, key: &str) -> Option<&'a str> {
self.into_iter()
.filter(|tag| tag.key == key)
.map(|tag| tag.value.as_ref())
.next()
}
}
The trait now consumes
self
, which would not be at all desirable, except for the fact that the only implementers ofIntoIterator<Item = &'a Tag>
seem to be borrowing types, so theself
that is destroyed is only a reference. I'm a bit wary because there is nothing (except convention) stopping someone implementing that for an owning type likeVec
.
如果你能找到某种方法来获取拥有值并返回对其的引用,那么你就发现了 Rust 内存安全中的一个关键漏洞。请参阅Is there any way to return a reference to a variable created in a function? .
Moving the lifetime parameter from the method (elided) to the trait is weird. I'm finding it hard to understand how the return value ends up with a sensible lifetime.
我不明白这种困惑。你已经明确指定了生命周期,那么在什么情况下它会不合理呢?您没有将其从方法中删除,只是将其添加到特征中,因为现在特征必须知道 'a
是来自特征本身“外部”的东西。
Why does
v.find_tag(...)
work? The receiver here is aVec
not a reference. How is Rust converting it to a reference?
与任何其他采用引用的方法调用在值上调用时的工作方式相同。请参阅What are Rust's exact auto-dereferencing rules?
关于generics - 如何为 &T 的所有可迭代对象实现一次特征(例如 Vec<T> 和 &[T]),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48146804/