rust - trait impl 的委派只能在夜间进行?
问题描述
我想将特征的实现委托Foo
给(单个元素)容器的内容Bar
,只有当它的通用内容已经实现Foo
(Bar<T: Foo>
)时。
pub trait Foo {
fn foo(&self) -> u8;
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialOrd, Ord, PartialEq, Eq)]
pub struct Bar<T> {
wrapped: T
}
impl Foo for Bar<T: Foo> {
fn foo(&self) -> u8 {
self.wrapped.foo()
}
}
结果是:
error[E0658]: associated type bounds are unstable
--> /home/fadedbee/test.rs:26:18
|
26 | impl Foo for Bar<T: Foo> {
| ^^^^^^
|
= note: see issue #52662 <https://github.com/rust-lang/rust/issues/52662> for more information
= help: add `#![feature(associated_type_bounds)]` to the crate attributes to enable
这只能在夜间进行,还是我只是使用了错误的语法?
解决方案
只是一个小的语法差异。
impl<T : Foo> Foo for Bar<T> {
fn foo(&self) -> u8 {
self.wrapped.foo()
}
}
impl
需要引入类型变量,然后我们在Bar
. 以上等价于更详细的
impl<T> Foo for Bar<T> where T : Foo {
fn foo(&self) -> u8 {
self.wrapped.foo()
}
}
在任何一种情况下,都会impl
引入类型变量。
推荐阅读
- typescript - 如何从打字稿续集设置非空属性
- pointers - 您可以将多个值的一部分或全部作为函数的指针返回吗?
- python - 使用 selenium 在 python 中动态更改 xpaths 该怎么办?
- ios - 将 Json 数据数组添加到 Realm
- sql - 如何在 oracle sql 中生成两个日期之间的所有星期日日期?
- mysql - 分发每个月Mysql中的所有行
- spring-mvc - Spring MVC 和 gradle,源服务器没有找到目标资源的当前表示,或者不愿意透露那个
- javascript - 关于设置 python 路径的 npm install 错误
- python - (Windows 8.1) 使用“Hey Google”来启用请求,而不是按 Enter
- firebase - Flutter:云消息未传递给主题订阅者