相关疑难解决方法(0)

什么"大小没有实现"是什么意思?

我写了以下代码:

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)

rust

35
推荐指数
2
解决办法
2万
查看次数

特征对象和特征的直接实现者的特征实现

我有一个结构,主要封装了一个向量:

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)

我想实现SolidGroup,但我希望能够使用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)

这是可行的,但是两次换行相同的代码不是惯用的解决方案。我一定缺少明显的东西吗?

就我而言,我测量了两个特征实现之间的显着性能差异,因此始终使用 …

traits rust

6
推荐指数
1
解决办法
783
查看次数

在创建该类型的线程局部变量的闭包中“使用来自外部函数的类型变量”

我正在尝试构建一个线程池,其中池中的每个线程都有一个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)

rust

1
推荐指数
1
解决办法
423
查看次数

如何编写一个知道实现者是 [u8] 的特征方法?

我正在实现一个特征&[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)

rust

1
推荐指数
1
解决办法
265
查看次数

标签 统计

rust ×4

traits ×1