我正在使用一些通用结构,如下所示:
pub struct Example<A, B, C, D, E, F> {
inner: OtherExample<A, B, C, D, E, F>
...
}
Run Code Online (Sandbox Code Playgroud)
在该结构的整个实现方法中,我必须不断引用这一巨大的类型集,如下所示:
impl<A, B, C, D, E, F> Example<A, B, C, D, E, F> {
pub fn get_inner(&self) -> &OtherExample<A, B, C, D, E, F> {
&self.inner
}
...
}
Run Code Online (Sandbox Code Playgroud)
我想知道是否有一种方法可以缩短所有这些通用类型的符号。为了便于阅读,我不能像上面的示例中那样只使用单个字母,所以我真的想在结构中创建一个泛型类型别名,如下所示:
pub struct Example<AliasedGenerics = <A, B, C, D, E, F>> {
inner: OtherExample<AliasedGenerics>
...
}
impl<AliasedGenerics = <A, B, C, D, E, F>> Example<AliasedGenerics> {
pub fn get_inner(&self) -> &OtherExample<AliasedGenerics> {
&self.inner
}
...
}
Run Code Online (Sandbox Code Playgroud)
这样我就不必继续编写非常长的行并提高通用实现的可读性。
在不了解更多上下文的情况下,我不能说这是否能解决您的问题,但您可以使用关联类型来执行类似的操作:
// Define the "alias"
pub trait GenericsSet { type A; type B; type C; }
pub struct Example<G: GenericsSet>(OtherExample<G>);
pub struct OtherExample<G: GenericsSet> { a: G::A, b: G::B, c: G::C, }
// I was a bit surprised that it is possible,
// but it seems you can even impose limits on some of the parameters
impl<G: GenericsSet<C = String>> Example<G> {
fn foo(&self) -> &str { &self.0.c }
fn get_inner(&self) -> &OtherExample<G> { &self.0 }
}
// Here, the illusion fades a bit:
// You'll need a type for each combination of types you want to use
struct MyGS1 {}
impl GenericsSet for MyGS1 { type A = (); type B = bool; type C = String; }
fn main() {
println!("{}", Example::<MyGS1>(OtherExample {a: (), b: true, c: "works".into() }).foo())
}
Run Code Online (Sandbox Code Playgroud)
不过,我建议不要在公共 API 中使用这个技巧。
| 归档时间: |
|
| 查看次数: |
3466 次 |
| 最近记录: |