Rust 中特质的平等约束。带有 Into的变体特征
我希望 ToKeyIter::Item 等于 ToKeyIter::KeyIter::Item 因为 KeyIter 应该实现 Iterator 特征。我无法做到这一点,因为 where 子句中的约束相等。这就是为什么我决定使用 Trait Into。
pub trait ToKeyIter {
type Item: Clone + Hash + Eq;
type KeyIter<'b>: Iterator where Self: 'b, <Self::KeyIter<'b> as Iterator>::Item: Into<Self::Item>;
fn key_iter<'a> (&'a self) -> Self::KeyIter<'a>
where <Self::KeyIter<'a> as Iterator>::Item: Into<Self::Item>;
}
该特征本身可以编译,但是当我尝试将其实现为 str 或 String 时,编译器会失败并显示“溢出评估需求”。
impl ToKeyIter for str {
type Item = char;
type KeyIter<'a> = Chars<'a>;
fn key_iter<'a> (&'a self) -> Chars<'a> {
self.chars()
}
}
impl ToKeyIter for String {
type Item = char;
type KeyIter<'a> = Chars<'a>;
fn key_iter<'a> (&'a self) -> Chars<'a> {
self.chars()
}
}
如果您能告诉我如何写这样的东西,
Key::Item == Key::KeyIter::Item
那就太好了。但我也想知道我应该做什么才能为带有 Into 特征的 str 和 String 提供正确的实现。
I want the ToKeyIter::Item be equal to ToKeyIter::KeyIter::Item as KeyIter should implement Iterator trait. I couldn't do it because with constraint equality in where clause. That's why I decided to use trait Into.
pub trait ToKeyIter {
type Item: Clone + Hash + Eq;
type KeyIter<'b>: Iterator where Self: 'b, <Self::KeyIter<'b> as Iterator>::Item: Into<Self::Item>;
fn key_iter<'a> (&'a self) -> Self::KeyIter<'a>
where <Self::KeyIter<'a> as Iterator>::Item: Into<Self::Item>;
}
The trait itself compiles, but when I try to impl it for str or String, the compiler fails with "overflow evaluating the requirement".
impl ToKeyIter for str {
type Item = char;
type KeyIter<'a> = Chars<'a>;
fn key_iter<'a> (&'a self) -> Chars<'a> {
self.chars()
}
}
impl ToKeyIter for String {
type Item = char;
type KeyIter<'a> = Chars<'a>;
fn key_iter<'a> (&'a self) -> Chars<'a> {
self.chars()
}
}
If you can tell how to write something like this
Key::Item == Key::KeyIter::Item
it will be great. But also I want to know what I should do to have correct impl for str and String with Into trait.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以指定
迭代&lt; item = self :: item&gt;
以获取所需的东西。参见You can specify the
Iterate<Item=Self::Item>
to obtain what you want. See the playground for a live version of this: