我写了以下代码:
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 Group<S> {
elements: Vec<S>
}
Run Code Online (Sandbox Code Playgroud)
我也有一个简单的特征,该特征也可用于其他结构:
trait Solid {
fn intersect(&self, ray: f32) -> f32;
}
Run Code Online (Sandbox Code Playgroud)
我想实现Solid的Group,但我希望能够使用Group都为相同的实现的名单Solid和混合实现的名单Solid。基本上我想同时使用Group<Box<Solid>>和Group<Sphere>(Sphere实现Solid)。
目前我正在使用这样的东西:
impl Solid for Group<Box<Solid>> {
fn intersect(&self, ray: f32) -> f32 {
//do stuff
}
}
impl<S: Solid> Solid for Group<S> {
fn intersect(&self, ray: f32) -> f32 {
//do the same stuff, code copy-pasted from previous impl
}
}
Run Code Online (Sandbox Code Playgroud)
这是可行的,但是两次换行相同的代码不是惯用的解决方案。我一定缺少明显的东西吗?
就我而言,我测量了两个特征实现之间的显着性能差异,因此始终使用 …
我正在尝试构建一个线程池,其中池中的每个线程都有一个thread_local! 可供该工作线程上的任务使用的类型。(T在下面的例子中)。该类的主要目的是资源T不需要Send,因为它将通过工厂方法在每个工作线程上本地构造,即 Send.
我的用例是在一个!Send数据库连接池上工作,但我试图使它在资源类型上通用T。
extern crate threadpool;
use std::sync::mpsc::channel;
use std::sync::Arc;
// A RemoteResource is a threadpool that maintains a threadlocal ?Send resource
// on every pool in the thread, which tasks sent to the pool can reference.
// It can be used e.g., to manage a pool of database connections.
struct RemoteResource<T, M>
where
M: 'static + Send + Sync + Fn() -> T,
{
pool: …Run Code Online (Sandbox Code Playgroud) 我正在实现一个特征&[u8],但无法self在特征实现中使用。我假设该特征无法检测类型,我应该使用一个where子句,但我不知道如何在没有实现者的情况下使用它。
use std::fmt::Debug;
pub trait Xor: Debug {
fn xor(&self, key_bytes: &[u8]) -> &[u8] {
for n in &self[..] {
dbg!(n);
}
unimplemented!()
}
}
impl Xor for [u8] {}
fn main() {
let xa = b"1234";
xa.xor(b"123");
}
Run Code Online (Sandbox Code Playgroud)
use std::fmt::Debug;
pub trait Xor: Debug {
fn xor(&self, key_bytes: &[u8]) -> &[u8] {
for n in &self[..] {
dbg!(n);
}
unimplemented!()
}
}
impl Xor for [u8] {}
fn main() {
let xa …Run Code Online (Sandbox Code Playgroud)