【问题标题】:associated type `Element` not found for `Self`未找到“Self”的关联类型“Element”
【发布时间】:2021-07-06 14:17:28
【问题描述】:

我正在尝试将to_be_bytes 方法包装到特征中(目前它们是直接从原始类型实现的),以便我可以在泛型类型上使用它。这是我的代码:

trait ToBeBytes {
    fn to_be_bytes(&self) -> [u8; mem::size_of::<Self>()];
}

问题出现在mem::size_of::&lt;Self&gt;(),编译器说是这样的

在编译时无法知道 Self 类型值的大小

我想出了一个叫做类型占位符的概念,所以我改成这个:

trait ToBeBytes {
    type Element;
    fn to_be_bytes(&self) -> [u8; mem::size_of::<Self::Element>()];
}

现在编译器说:

未找到 Self 的关联类型 Element

我尝试了教程中的示例:

pub trait Iterator {
    type Item;

    fn next(&mut self) -> Option<Self::Item>;
}

然后编译。

那么我的代码和示例之间有什么区别?我怎样才能实现我的目标(将to_be_bytes 包装成特征)?

【问题讨论】:

标签: rust


【解决方案1】:

编译您的代码会导致以下错误:

error: generic parameters may not be used in const operations
 --> src/lib.rs:4:55
  |
4 |     fn to_be_bytes(&self) -> [u8; std::mem::size_of::<Self>()];
  |                                                       ^^^^ cannot perform const operation using `Self`
  |
  = note: type parameters may not be used in const expressions
  = help: use `#![feature(const_generics)]` and `#![feature(const_evaluatable_checked)]` to allow generic const expressions

果然,您的代码使用#![feature(const_evaluatable_checked, const_generics)] 编译。

【讨论】:

    【解决方案2】:

    这里的问题是 rust 还不完全支持常量泛型,根据blog

    目前,const 参数只能由 const 实例化 以下形式的参数:

    • 独立的 const 参数。
    • 文字(即整数、布尔值或 字符)。
    • 一个具体的常量表达式(由 {} 括起来),涉及 没有通用参数。 例如:
    fn foo<const N: usize>() {}
    
    fn bar<T, const M: usize>() {
        foo::<M>(); // ok: `M` is a const parameter
        foo::<2021>(); // ok: `2021` is a literal
        foo::<{20 * 100 + 20 * 10 + 1}>(); // ok: const expression contains no generic parameters
        
        foo::<{ M + 1 }>(); // error: const expression contains the generic parameter `M`
        foo::<{ std::mem::size_of::<T>() }>(); // error: const expression contains the generic parameter `T`
        
        let _: [u8; M]; // ok: `M` is a const parameter
        let _: [u8; std::mem::size_of::<T>()]; // error: const expression contains the generic parameter `T` 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多