首页 > 解决方案 > 如何声明采用具有类型参数的特征的函数的实现?

问题描述

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

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 };
}

操场

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

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函数的实现?

标签: rust

解决方案


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

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

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

impl<T> Connection<T> {
    pub fn is_connected_to<I: PartialEq>(&self, point: T) -> bool
    where
        T: Point<I>
    {
        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
    };
}

推荐阅读