rust - 具有关联类型的别名特征

标签 rust

<分区>

是否可以创建具有指定关联类型的特征别名?我正在使用来自类似问题 Type alias for multiple traits 的方法

trait Trait {
    type Item;
}

fn print<T>(value: T) where T: Trait<Item=char> {
}

trait Alias: Trait {}
impl<T: Trait<Item=char>> Alias for T {}

fn print_alias<T: Alias>(value: T) {
    print(value)
}

fn main() {
}

但是编译失败并出现以下错误:

<anon>:12:5: 12:10 error: type mismatch resolving `<T as Trait>::Item == char`:
 expected associated type,
    found char [E0271]
<anon>:12     print(value)
              ^~~~~
<anon>:12:5: 12:10 note: required by `print`
<anon>:12     print(value)
              ^~~~~
error: aborting due to previous error

围栏链接:http://is.gd/LE4h6a

最佳答案

@Shepmaster的方案解决了本地问题;但你必须指定 where T: Alias<Item=char>每一次。或者,您可以通过要求所有 Alias 来全局解决它工具 Trait<Item=char> :

trait Alias: Trait<Item=char> {}
impl<T: Trait<Item=char>> Alias for T {}

选择全局解决方案还是本地解决方案完全取决于您。

关于rust - 具有关联类型的别名特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30424100/

相关文章:

rust - `return` 语句不应该返回 `!`(从不输入)吗?

rust - "Expected associated type, found ` u32 `"将参数的生命周期用作 where 绑定(bind)中的特征参数

rust - 启用LogTracer会导致 panic

rust - `&mut retval` 和 `retval as *const T as *mut T` 和有什么区别?

rust - 我们可以在过程宏属性中获取调用者的源代码位置吗?

rust - 是否可以返回或什么都不退?

multithreading - 为什么 Rust 会阻止多重可变引用?

python - 如何在 PyO3 中实现 python 运算符

rust - 将 Result 转换为自定义 Fail impl 的惯用方法是什么?

gtk - 在 Rust 中处理 GTK+ 事件的替代方法