本文介绍了为什么我收到“从未使用过参数 [E0392]"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to implement an Octree in Rust. The Octree is generic over a type with a constraint that it should implement a generic trait:

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,
}

这是一个 在 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'".

Removing the U from the signature results in "undeclared type name 'U'".

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

Am I doing something wrong or is it a bug? How to do this properly?

推荐答案

我不相信你在这里想要另一个泛型,你想要关联类型:

I don't believe you want another generic here, 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> 可能是间接的一级额外 - 你可以只使用 Vec>.

As an aside, Vec<Box<Octree<T>>> is probably one level extra of indirection — you can just use Vec<Octree<T>>.

这篇关于为什么我收到“从未使用过参数 [E0392]"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:49