如何声明采用具有类型参数的特征的函数的实现?

时间:2018-07-29 20:08:43

标签: rust

我有一个具有通用类型的特征。我想定义一个具有满足该特征的属性的结构,并想在该结构中实现一个使用该特征内部功能的函数:

pub trait Point<I> {
    fn id(&self) -> I;
}

pub struct Connection<T> {
    pub to: T,
}

impl<T: Point> Connection<T> {
    pub fn is_connected_to(&self, point: T) -> bool {
        self.to.id() == point.id()
    }
}

pub fn main() {
    struct SimplePoint;
    impl Point<char> for SimplePoint {
        fn id(&self) -> char {
            return 'A';
        }
    }

    let a = SimplePoint {};

    let conn = Connection { to: a };
}

playground

如果我尝试运行此代码,则会收到错误消息:

error[E0243]: wrong number of type arguments: expected 1, found 0
 --> src/main.rs:9:9
  |
9 | impl<T: Point> Connection<T> {
  |         ^^^^^ expected 1 type argument

如果我尝试添加通用类型:

impl<T: Point<I>> Connection<T> {
    pub fn is_connected_to(&self, point: T) -> bool {
        self.to.id() == point.id()
    }
}

然后我得到这个错误:

error[E0412]: cannot find type `I` in this scope
 --> src/main.rs:9:15
  |
9 | impl<T: Point<I>> Connection<T> {
  |               ^ did you mean `T`?

如果我尝试定义类型I

impl<I, T: Point<I>> Connection<T> {
    pub fn is_connected_to(&self, point: T) -> bool {
        self.to.id() == point.id()
    }
}

编译器告诉我I是不受约束的:

error[E0207]: the type parameter `I` is not constrained by the impl trait, self type, or predicates
 --> src/main.rs:9:6
  |
9 | impl<I, T: Point<I>> Connection<T> {
  |      ^ unconstrained type parameter

我应该如何声明is_connected_to函数的实现?

1 个答案:

答案 0 :(得分:5)

泛型类型必须是单态的:每个泛型类型必须解析为具体类型。如果没有约束,编译器将无法知道您想要的具体类型。您必须将泛型类型放入函数中:

basic authentication