我有一个特点叫Sleep:
pub trait Sleep {
fn sleep(&self);
}
Run Code Online (Sandbox Code Playgroud)
我可以Bed为每个结构提供不同的实现,但事实证明大多数人以很少的方式睡觉.你可以睡在床上:
pub trait HasBed {
fn sleep_in_bed(&self);
fn jump_on_bed(&self);
}
impl Sleep for HasBed {
fn sleep(&self) {
self.sleep_in_bed()
}
}
Run Code Online (Sandbox Code Playgroud)
如果你露营,你可以睡在帐篷里:
pub trait HasTent {
fn sleep_in_tent(&self);
fn hide_in_tent(&self);
}
impl Sleep for HasTent {
fn sleep(&self) {
self.sleep_in_tent()
}
}
Run Code Online (Sandbox Code Playgroud)
有一些古怪的案例.我有一个可以靠墙站着睡觉的朋友,但大多数人大多数时候会陷入一些简单的情况.
我们定义一些结构并让它们Sleep:
struct Jim;
impl HasBed for Jim {
fn sleep_in_bed(&self) {}
fn jump_on_bed(&self) {}
}
struct Jane;
impl HasTent for Jane {
fn …Run Code Online (Sandbox Code Playgroud) 我想实现这个Shl特性Vec,代码如下.这会使事情变得vec << 4可能,这对于它来说是个不错的选择vec.push(4).
use std::ops::Shl;
impl<T> Shl<T> for Vec<T> {
type Output = Vec<T>;
fn shl(&self, elem: &T) -> Vec<T> {
self.push(*elem);
*self
}
}
fn main() {
let v = vec![1, 2, 3];
v << 4;
}
Run Code Online (Sandbox Code Playgroud)
编译失败,出现以下错误:
无法提供扩展实现,其中特征和类型都未在此包中定义[E0117]
要么
type参数
T必须用作某些本地类型的类型参数(例如MyStruct<T>); 只有当前包中定义的特征才能为类型参数实现[E0210]
据我了解,我必须修补stdlib,更具体地来说是collections::vec板条箱.有没有其他方法可以更改此代码以成功编译?
我有以下代码:
extern crate futures; // 0.1.24
use futures::Future;
use std::io;
struct Context;
pub trait MyTrait {
fn receive(context: Context) -> Future<Item = (), Error = io::Error>;
}
pub struct MyStruct {
my_trait: MyTrait,
}
Run Code Online (Sandbox Code Playgroud)
当我尝试编译它时,我收到错误消息:
error[E0038]: the trait `MyTrait` cannot be made into an object
--> src/lib.rs:13:5
|
13 | my_trait: MyTrait,
| ^^^^^^^^^^^^^^^^^ the trait `MyTrait` cannot be made into an object
|
= note: method `receive` has no receiver
Run Code Online (Sandbox Code Playgroud)
我想我知道它为什么会发生,但我如何从结构中引用特征呢?可能吗?也许还有其他方法可以实现相同的行为?