【问题标题】:How to handle error: nested generic parameters is never used [duplicate]如何处理错误:从不使用嵌套泛型参数 [重复]
【发布时间】:2021-05-02 01:58:24
【问题描述】:

试图将 T 用作另一个泛型参数 this way 的特征的泛型参数:

pub trait Foo<T> {
    fn foo() -> T;
}

struct Bar<T, F: Foo<T>> {
    f: F,
}

fn main() {
}

失败:

error[E0392]: parameter `T` is never used
 --> src/main.rs:5:12
  |
5 | struct Bar<T, F: Foo<T>> {
  |            ^ unused parameter
  |
  = help: consider removing `T`, referring to it in a field, or using a marker such as `PhantomData`

编译器建议使用PhantomData:

use core::marker::PhantomData;

pub trait Foo<T> {
    fn foo() -> T;
}

struct Bar<T, F: Foo<T>> {
    f: F,
    t: PhantomData<T>,
}

fn main() {
}

难道没有比创建一个具有奇怪名称特征的假字段更优雅的方法来处理这个问题吗?

【问题讨论】:

  • 抽象地回答这个问题有点困难。 struct Bar应该具备哪些特性,是否应该实现trait Foo
  • 不,它只需要一个实现 Foo 的字段。
  • 重复问题中的答案实际上很糟糕。因此,每次实例化结构时都需要使用 PhantomType 实例化字段。

标签: rust traits


【解决方案1】:

我认为这里的问题主要是语法问题。以下代码展示了如何创建一个结构,其中一个字段受 trait 约束。

pub trait Foo {
    fn foo();
}

#[derive(Debug)]
struct Bar<F> where F: Foo {
    f: F,
}

// an example so we can actually construct a Bar
impl Foo for u32 {
    fn foo() {}
}

fn main() {
    let b = Bar { f: 2 };
    println!("{:?}", b);
}

【讨论】:

  • Foo 有一个通用参数。它没有在问题中使用,因为它是 MWE,但在我的现实生活问题中它是。当然,没有 Foo 的泛型参数,也没有什么困难。
  • 我认为您可能使 MWE 有点太小了;)我需要更多信息来改进答案。
  • 我认为这不能回答问题,您只是删除了T
  • 是的,我读的太快了,太专注于如何让代码正常工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-10
  • 1970-01-01
  • 2022-11-07
  • 1970-01-01
  • 2020-08-15
  • 1970-01-01
  • 2022-11-23
相关资源
最近更新 更多