[英]Is it possible to create a type alias in a struct in Rust?
我正在使用一些通用結構,如下所示:
pub struct Example<A, B, C, D, E, F> {
pub inner: OtherExample<A, B, C, D, E, F>
...
}
在這個結構的整個實現方法中,我必須不斷地引用大量的類型,如下所示:
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
}
...
}
我想知道是否有辦法縮短所有這些泛型類型的符號。 為了便於閱讀,我不能像上面的例子那樣只使用單個字母,所以我真的想在結構中創建一個泛型類型別名,如下所示:
pub struct Example<AliasedGenerics = <A, B, C, D, E, F>> {
pub inner: OtherExample<AliasedGenerics>
...
}
impl<AliasedGenerics = <A, B, C, D, E, F>> Example<AliasedGenerics> {
pub fn get_inner(&self) -> &OtherExample<AliasedGenerics> {
&self.inner
}
...
}
這樣我就不必一直寫很長的行並提高通用實現的可讀性。
在不了解更多上下文的情況下,我不能說這是否會解決您的問題,但您可以使用關聯類型來做一些類似的事情:
// 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())
}
不過,我建議不要在公共 API 中使用此技巧。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.