简体   繁体   English

当两个泛型类型相同时告诉 Rust 编译器

[英]Tell the Rust compiler when two generic types are the same

I'm wondering if it is possible to tell to the Rust compiler that two generic types are the same.我想知道是否可以告诉 Rust 编译器两种泛型类型相同。

In the specific case, I have a trait with a generic method and I want to implement a struct that has the same generic type as field, like in the following example:在特定情况下,我有一个泛型方法的特征,我想实现一个与字段具有相同泛型类型的结构,如下例所示:

trait Trait {
    fn foo<T>(&self, t: T) -> T;
}

struct Struct<T> {
    t: T
}

impl<T> Trait for Struct<T> {
    fn foo<U>(&self, t: U) {
        self.t
    }
}

Ofc here I have a compiler error because it expects U but have a T. How can I handle this case? Ofc 在这里我有一个编译器错误,因为它需要 U 但有一个 T。我该如何处理这种情况?

Moving the generic outside foo creating Trait<T> is not an option.移动通用外部 foo 创建Trait<T>不是一种选择。

You could probably use associated types:您可能会使用关联类型:

trait Trait {
    type U;
    fn foo(&self, t: Self::U) -> Self::U;
}

struct Struct<T> {
    t: T
}

impl<T: Copy> Trait for Struct<T> {
    type U = T;
    fn foo(&self, t: T) -> T {
        self.t
    }
}

Playground 操场

PS: I added an extra T: Copy because T needs to be Copy to return self.t as it is a shared ref. PS:我添加了一个额外的T: Copy因为T需要是Copy才能返回self.t因为它是共享参考。

fn foo<T>(&self, t: T) -> T;

in a trait means the method must work for all T , and your struct's field can't possibly have all of those types at the same time! in a trait 意味着该方法必须适用于所有T ,并且您的结构字段不可能同时具有所有这些类型!

That is, this code will compile given the trait and struct definition:也就是说,这段代码将根据 trait 和 struct 定义进行编译:

fn main() {
    let x: Struct<i32> = Struct { t: 0 };
    let y: &str = x.foo("abc");
    let z: [i32; 2] = x.foo([0,0]);
}

and obviously y and z can't be xt .显然yz不能是xt

(after writing the answer, I see the point has already been made in mcarton's comment; I will delete it if he asks, but hopefully it's a bit clearer this way without requiring dyn ). (在写完答案后,我看到 mcarton 的评论中已经提出了这一点;如果他问,我会删除它,但希望这种方式更清楚一点,而不需要dyn )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM