我写了以下代码:
use std::io::{IoResult, Writer};
use std::io::stdio;
fn main() {
let h = |&: w: &mut Writer| -> IoResult<()> {
writeln!(w, "foo")
};
let _ = h.handle(&mut stdio::stdout());
}
trait Handler<W> where W: Writer {
fn handle(&self, &mut W) -> IoResult<()>;
}
impl<W, F> Handler<W> for F
where W: Writer, F: Fn(&mut W) -> IoResult<()> {
fn handle(&self, w: &mut W) -> IoResult<()> { (*self)(w) }
}
Run Code Online (Sandbox Code Playgroud)
然后rustc在我的终端:
$ rustc writer_handler.rs
writer_handler.rs:8:15: 8:43 error: the trait `core::marker::Sized` is not …Run Code Online (Sandbox Code Playgroud) 我想为引用和非引用类型实现一个特征。我是否必须两次实现这些功能,或者这样做不是惯用的?
这是演示代码:
struct Bar {}
trait Foo {
fn hi(&self);
}
impl<'a> Foo for &'a Bar {
fn hi(&self) {
print!("hi")
}
}
impl Foo for Bar {
fn hi(&self) {
print!("hi")
}
}
fn main() {
let bar = Bar {};
(&bar).hi();
&bar.hi();
}
Run Code Online (Sandbox Code Playgroud) 假设有一个 trait,它的方法都只接受 的引用self,比如
trait Trait {
fn foo(&self) -> i32;
}
Run Code Online (Sandbox Code Playgroud)
我想有这样的特点实施了两个Option<T>和Option<&T>(因为我总是无法承受所有权),用一个简单的实现,如
impl<T: Trait> Trait for Option<T> {
fn foo(&self) -> i32 {
if let Some(inner) = self { return inner.foo(); }
0
}
}
impl<T: Trait> Trait for Option<&T> {
fn foo(&self) -> i32 {
if let Some(inner) = self { return inner.foo(); }
0
}
}
Run Code Online (Sandbox Code Playgroud)
但是,这样做会产生以下错误:
error[E0119]: conflicting implementations of trait `Trait` for type `std::option::Option<&_>`:
--> option.rs:12:1
|
5 | impl<T: …Run Code Online (Sandbox Code Playgroud)