小编Fer*_*rio的帖子

为什么关联的常量不依赖于类型参数?

这仅仅是当前的限制还是有技术原因?由于泛型函数被编译为专用代码,我看不出应该阻止它工作的内容.它在该main功能中也可以正常工作.

示例(游乐场):

#![feature(associated_consts)]
trait HasNumber<T> {
    const Number: usize;
}

enum One {}
enum Two {}

enum Foo {}

impl<T> HasNumber<One> for T {
    const Number: usize = 1;
}

impl<T> HasNumber<Two> for T {
    const Number: usize = 2;
}

fn use_number<T, H: HasNumber<T>>() {
    let a: [u8; H::Number] = unsafe { ::std::mem::uninitialized() };
}

fn main() {
    let a: [u8; <Foo as HasNumber<One>>::Number] = unsafe { ::std::mem::uninitialized() };
    println!("{}", <Foo as HasNumber<One>>::Number); 
    println!("{}", <Foo …
Run Code Online (Sandbox Code Playgroud)

rust

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

在特征对象上使用回调

我正在尝试在特征对象上使用回调函数.我将我的问题减少到以下代码(围栏):

trait Caller {
    fn call(&self, call: fn(&Caller)) where Self: Sized {
        call(self)
    }
}

struct Type;
impl Caller for Type {}

fn callme(_: &Caller) {}

fn main() {
    let caller: Box<Caller> = Box::new(Type);
    caller.call(callme); // does not work
    //callme(&*caller);  // works
}
Run Code Online (Sandbox Code Playgroud)

结果

<anon>:14:12: 14:24 error: the trait `core::marker::Sized` is not implemented for the type `Caller` [E0277]
<anon>:14     caller.call(callme); // does not work
                     ^~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

添加Sized绑定到Caller结果:

<anon>:3:14: 3:18 error: cannot convert to a trait …
Run Code Online (Sandbox Code Playgroud)

rust

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

从实现`Error`特征的对象实现泛型转换

我无法获得以下代码进行编译.

  • 我收到一个From已经实现的错误.
  • 如果我删除了手动impl,From我得到了From未实现的错误.
  • 如果我没有实现Error它工作正常.

我想这是由于impl<T> From<T> for T核心的空白.我应该如何解决这个问题?不实施Error不是一个真正的选择.

代码(游乐场)

use std::fmt;
use std::io;
use std::error::Error;

#[derive(Debug)]
enum ErrorType {
    Other(Box<Error>)
}

impl fmt::Display for ErrorType {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.write_str("not implemented")
    }
}

impl Error for ErrorType {
    fn description(&self) -> &str {
        use self::ErrorType::*;
        match *self {
            Other(ref err) => err.description(),
        }
    }
}

impl<E: Error + 'static> From<E> for …
Run Code Online (Sandbox Code Playgroud)

rust

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

标签 统计

rust ×3