有没有办法解决未使用的类型参数? [英] Is there any way to work around an unused type parameter?

查看:47
本文介绍了有没有办法解决未使用的类型参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

trait Trait<T> {}

struct Struct<U>;

impl<T, U: Trait<T>> Struct<U> {}

错误:

error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates
 --> src/main.rs:5:6
  |
5 | impl<T, U: Trait<T>> Struct<U> {}
  |      ^ unconstrained type parameter

似乎RFC 447 禁止这种模式;有没有办法解决这个问题?我认为可以通过将 T 更改为关联类型来解决这个问题,但这会阻止我进行多分派.

It seems that RFC 447 prohibits this pattern; is there any way to work around this? I think it could be solved by changing T to an associated type, but that would prevent me from doing multidispatch.

推荐答案

结构中未使用的类型参数可以使用 PhantomData:

A type parameter that's unused in the struct can use PhantomData:

struct Struct<U> {
    _marker: PhantomData<U>,
}

impl<U> Struct<U> {
    fn example<T>(&self)
    where
        U: Trait<T>,
    {
        // use `T` and `U`
    }
}

这篇关于有没有办法解决未使用的类型参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆