特征委托只能在夜间进行吗?
Delegation of trait impl only possible in nightly?
我想将特征 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
都会引入类型变量。
我想将特征 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
都会引入类型变量。