gpt4 book ai didi

rust - 是否可以组合嵌套关联类型的边界?

转载 作者:行者123 更新时间:2023-11-29 07:55:33 25 4
gpt4 key购买 nike

我处理几个具有关联类型的特征:

trait Foo {
type FooType;
}

trait Bar {
type BarType;
}

trait Baz {
type BazType;
}

我有一个函数需要绑定(bind)那些关联类型。我可以这样做 ( Playground ):

fn do_the_thing<T>(_: T)
where
T: Foo,
T::FooType: Bar,
<T::FooType as Bar>::BarType: Baz,
<<T::FooType as Bar>::BarType as Baz>::BazType: Clone,
{}

这行得通,但是非常冗长。一个问题是我需要使用 <Type as Trait>消除一些路径歧义的语法,尽管这不是必需的。此问题已被报告 here .

我想知道是否可以缩短上述函数的定义。我想,也许可以将所有边界合并为一个边界:

fn do_the_thing<T>(_: T)
where
T: Foo<FooType: Bar<BarType: Baz<BazType: Clone>>>,
{}

但这会导致语法错误:

error: expected one of `!`, `(`, `+`, `,`, `::`, `<`, or `>`, found `:`
--> src/main.rs:16:19
|
16 | T: Foo<FooType: Bar<BarType: Baz<BazType: Clone>>>,
| ^ expected one of 7 possible tokens here

有没有办法以某种方式压缩边界?

最佳答案

这现在可以通过不稳定的特性 associated_type_bounds ( tracking issue ) 实现。

#![feature(associated_type_bounds)]

fn do_the_thing<T>(_: T)
where
T: Foo<FooType: Bar<BarType: Baz<BazType: Clone>>>,
{}

( Playground )

关于rust - 是否可以组合嵌套关联类型的边界?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50782704/

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