我有以下定义HList:
pub trait Data: Any + Debug {}
impl<T: Any + Debug> Data for T {}
/// The empty `HList`.
pub struct Nil;
/// An `HList` with `H` at position 0, and `T` as the rest of the list.
pub struct Cons<H, T> {
head: PhantomData<H>,
tail: PhantomData<T>,
}
/// A marker trait that `Nil` and `Cons<H, T>` satisfies.
pub trait HList {}
impl HList for Nil {}
impl<H, T: HList> HList for Cons<H, T> {}
Run Code Online (Sandbox Code Playgroud)
如何通过将它们附加到最后来构造类型?
将它们作为第一个元素插入是微不足道的:
trait Prepend<D: Data>: Sized {
fn prepend(self, item: D) -> Cons<D, Self>;
}
impl<D: Data> Prepend<D> for Nil {
fn prepend(self, item: D) -> Cons<D, Nil> {
Cons {
head: PhantomData,
tail: PhantomData,
}
}
}
impl<D: Data, H, T: HList> Prepend<D> for Cons<H, T> {
fn prepend(self, item: D) -> Cons<D, Cons<H, T>> {
Cons {
head: PhantomData,
tail: PhantomData,
}
}
}
Run Code Online (Sandbox Code Playgroud)
但最后添加元素,同时保持相同的结构似乎很难.
Nil.prepend(true).prepend(3).prepend("string")
-> Cons<&'static str, Cons<i32, Cons<bool, Nil>>>
Nil.push("string").push(3).push(true)
-> Cons<&'static str, Cons<i32, Cons<bool, Nil>>>
Run Code Online (Sandbox Code Playgroud)
我知道答案是某种递归函数,它寻找Nil列表中的最后一个并在那里添加当前值,但是我很难为使用这种递归函数的特征定义一个函数.
假设我们Push在方法push中有一个特性,它HList在最里面的括号中添加了一个元素:
pub trait Push<?> {
fn push(self?, el: item) -> ?;
}
Run Code Online (Sandbox Code Playgroud)
如何构建它?
使用关联类型的递归似乎可以解决问题:
trait Append<D: Data> {
type Result;
fn append(self, item: D) -> Self::Result;
}
impl<D:Data> Append<D> for Nil {
type Result = Cons<D, Nil>;
fn append(self, item: D) -> Self::Result {
Cons {
head: PhantomData,
tail: PhantomData,
}
}
}
impl<D:Data, H, T:HList+Append<D>> Append<D> for Cons<H,T> {
type Result = Cons<H, <T as Append<D>>::Result>;
fn append(self, item: D) -> Self::Result {
Cons {
head: PhantomData,
tail: PhantomData,
}
}
}
Run Code Online (Sandbox Code Playgroud)