【问题标题】:Why am I getting "parameter is never used [E0392]"?为什么我会收到“从未使用过的参数 [E0392]”?
【发布时间】:2015-11-10 06:25:58
【问题描述】:

我正在尝试在 Rust 中实现八叉树。八叉树是泛型的,它有一个约束,它应该实现一个泛型特征:

pub trait Generable<U> {
    fn generate_children(&self, data: &U) -> Vec<Option<Self>>;
}

pub enum Octree<T, U>
where
    T: Generable<U>,
{
    Node {
        data: T,
        children: Vec<Box<Octree<T, U>>>,
    },
    Empty,
    Uninitialized,
}

这是simplified example reproducing the issue on the Playground

这会产生一个错误:

error[E0392]: parameter `U` is never used
 --> src/main.rs:5:20
  |
5 | pub enum Octree<T, U>
  |                    ^ unused type parameter
  |
  = help: consider removing `U` or using a marker such as `std::marker::PhantomData`

从签名中删除 U 会导致“未声明的类型名称 'U'”。

我做错了什么还是一个错误?如何正确执行此操作?

【问题讨论】:

  • 看起来像是编译器的一个限制,您可以通过使用PhantomData 来解决它,添加一个“假”成员PhantomData&lt;*const U&gt;,同时等待更明确的答案。
  • 这有帮助,谢谢。虽然能够在没有 PhantomData 的情况下使用这些结构会很好;)
  • 不客气 :) 我真的很想知道您的代码是应该被拒绝还是编译器错误...
  • 我在 Github 上发现了一个看起来相似的问题 (github.com/rust-lang/rust/issues/26283),那里的人似乎认为这是编译器的限制,但我不确定这是否真的相同。 ..

标签: rust


【解决方案1】:

我不相信你想要另一个泛型,you want an associated type

pub trait Generable {
    type From;
    fn generate_children(&self, data: &Self::From) -> Vec<Option<Self>>
    where
        Self: Sized;
}

pub enum Octree<T>
where
    T: Generable,
{
    Node {
        data: T,
        children: Vec<Box<Octree<T>>>,
    },
    Empty,
    Uninitialized,
}

fn main() {}

顺便说一句,Vec&lt;Box&lt;Octree&lt;T&gt;&gt;&gt; 可能是一个额外的间接级别 - 您可以使用 Vec&lt;Octree&lt;T&gt;&gt;

【讨论】:

  • 从1.31.1开始,我们需要在Self上添加Sizedpub trait Generable where Self:Sized { ...
猜你喜欢
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 2016-08-08
  • 2011-10-08
  • 1970-01-01
  • 2020-07-31
  • 1970-01-01
  • 2021-08-19
相关资源
最近更新 更多