gpt4 book ai didi

rust - 如何明确说明关联类型应该是什么?

转载 作者:行者123 更新时间:2023-12-04 13:26:43 25 4
gpt4 key购买 nike

我有一个类似于 Iterator 的特征,以及它周围的包装器:

pub struct Wrapped<I: Iterator>(I);
包装迭代器上的许多函数使用 impl-trait 返回新的包装迭代器。 .
impl <I: Iterator> Wrapped<I> {
pub fn foo(self) -> Wrapped<impl Iterator<Item=Foo<I::Item>>> {...}
pub fn bar(self) -> Wrapped<impl Iterator<Item=Bar<I::Item>>> {...}
}
这样一段时间后,用户就很容易忘记调用代码中的迭代器项是什么(例如,对于像 my_wrapped.foo().bar().bar().foo() 这样的表达式)。
我想给用户一种方法来明确指定他们期望的类型 Item如果不是那种类型,则会出现编译时错误:
let y = x.foo().bar().bar().foo().assert_item_type::<Foo<Bar<Bar<Foo<X>>>>>()
但到目前为止,我发现这样做的唯一方法有点奇怪和丑陋。有更干净的方法吗?
pub trait Is {
type Myself;
}

impl<T> Is for T {
type Myself = T;
}

impl <I: Iterator> Wrapped<I> {
pub fn assert_item_type<Item: Is<Myself = I::Item>>(self) -> Self {
self
}
}

最佳答案

如果你不介意使用一个独立的函数,你可以使用类似的方法而不需要任何特征:

fn assert_item_type<I: Iterator<Item=T>, T>(x: Wrapped<I>) -> Wrapped<I> {
x
}


let y = assert_item_type::<_, Foo<Bar<Bar<Foo<X>>>>>(x.foo().bar().bar().foo());
不幸的是它是 currently not possible替换 I assert_item_type 中的类型参数与 impl Iterator (这将摆脱 turbofish 中的下划线)作为编译器 does not allow usimpl Trait 时提供明确的泛型参数用于论证位置。
如果在编译器中引入此功能,则可以(假设)定义该函数并将其用作:
fn assert_item_type<T>(x: Wrapped<impl Iterator<Item=T>>) -> Wrapped<impl Iterator<Item=T>> {
x
}


let y = assert_item_type::<Foo<Bar<Bar<Foo<X>>>>>(x.foo().bar().bar().foo());
Playground

关于rust - 如何明确说明关联类型应该是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68023521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com