是否可以指定两个类型参数是不同类型? [英] Is it possible to specify that two type parameters are different types?

查看:75
本文介绍了是否可以指定两个类型参数是不同类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用map方法的简单包装器结构.我也有一个错误枚举层次结构,在其中实现了From以便能够将Error1转换为Error2,从而允许try!宏自动为我转换:

I have a simple wrapper structure with a map method. I also have a hierarchy of error enums where I've implemented From to be able to convert an Error1 to an Error2, allowing the try! macro to automatically convert for me:

struct Span<T>(T);

impl<T> Span<T> {
    fn map<F, U>(self, f: F) -> Span<U>
        where F: FnOnce(F) -> U
    {
        Span(f(self.0))
    }
}

enum Error1 { One }
enum Error2 { Two }

impl From<Error1> for Error2 {
    fn from(v: Error1) -> Error2 { Error2::Two }
}

我希望能够添加From实现,这样我也可以自动转换Span结构的内部:

I'd like to be able to add a From implementation so that I can also automatically convert the insides of the Span structure:

impl<T,U> From<Span<T>> for Span<U>
    where U: From<T>
{
    fn from(v: Span<T>) -> Span<U> {
        v.map(|v| v.into())
    }
}

不幸的是,此操作失败:

error[E0119]: conflicting implementations of trait `std::convert::From<Span<_>>` for type `Span<_>`:
  --> src/main.rs:18:1
   |
18 |   impl<T,U> From<Span<T>> for Span<U>
   |  _^ starting here...
19 | |     where U: From<T>
20 | | {
21 | |     fn from(v: Span<T>) -> Span<U> {
22 | |         v.map(|v| v.into())
23 | |     }
24 | | }
   | |_^ ...ending here
   |
   = note: conflicting implementation in crate `core`

错误消息没有指向 From ,但我猜就是这个了:

The error message doesn't point to a specific implementation of From, but my guess is it's this one:

impl<T> From<T> for T

如果我的TU恰好是相同的具体类型,则我的实现可能会发生冲突.有什么办法可以实现所有TU的特征,其中T!= U?

And that my implementation could conflict if my T and U happen to be the same concrete type. Is there any way I can implement my trait for all T and U where T != U?

推荐答案

不幸的是,这还不可能,并且尚未真正确定解决此问题的最佳方法.与这种情况稍微相关的一个建议是负边界(特别是平等边界),但我认为这太复杂了.有关该主题的更多信息,请参见最新问题.不同的想法,包括专业化.

Unfortunately this is not yet possible and the best approach to this problem has not really been decided yet. One proposal that is slightly relevant to this situation is the idea of negative bounds (specifically equality bounds), but I think it has been deemed too complex. See the latest issue on the subject for more information, where the team members are considering different ideas, including specialization.

这篇关于是否可以指定两个类型参数是不同类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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