Rust 的专业化与相关类型的效果很差,我想知道替代方案
特质:
pub trait IntoConfig<T, U>
where T: AsRef<[u8]> + AsRef<Path>,
U: IntoIterator<Item=T>,
<Self as IntoConfig<T, U>>::Matches: AsRef<[u8]>,
<Self as IntoConfig<T, U>>::Path: AsRef<Path>
{
type Path;
type Matches;
type Error;
fn to_config(self) -> Result<Config<Self::Path, Self::Matches>, Self::Error>;
}
我需要为我的配置创建者特征优化实现。但专攻防锈 关联类型的效果很差。
我的认识:
auto trait NonOptConfGen {}
impl<T> ! NonOptConfGen for &[T] {}
impl<T, U> IntoConfig<T, U> for U
where T: AsRef<[u8]> + AsRef<Path> + AsRef<str>,
U: IntoIterator<Item=T>,
Self: NonOptConfGen
{
type Path = T;
type Matches = String;
type Error = &'static str;
fn to_config(self) -> Result<Config<Self::Path, Self::Matches>, Self::Error> {
...
}
}
impl<'a, T> IntoConfig<&'a T, &'a [T]> for &'a [T]
where T: AsRef<[u8]> + AsRef<Path> + AsRef<str>,
{
type Path = &'a T;
type Matches = &'a str;
type Error = &'static str;
fn to_config(self) -> Result<Config<Self::Path, Self::Matches>, Self::Error> {
...
}
}
但是当我尝试介绍专业化的第二级时,一切 由于语言中缺乏“负面约束”而变得更加复杂。
我的决定:
auto trait NonOptConfGenT1 {}
auto trait NonOptConfGen {}
impl<T> ! NonOptConfGen for &[T] {}
impl<T: Copy> ! NonOptConfGenT1 for &[T] {}
和
impl<T, U> IntoConfig<T, U> for U
where T: AsRef<[u8]> + AsRef<Path> + AsRef<str>,
U: IntoIterator<Item=T>,
Self: NonOptConfGen + NonOptConfGenT1
,
impl<'a, T> IntoConfig<&'a T, &'a [T]> for &'a [T]
where T: AsRef<[u8]> + AsRef<Path> + AsRef<str>,
Self: NonOptConfGenT1
至于我,我的决定是次优的。还能做什么?