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 };
}
(操场)
如果我尝试运行此代码,则会收到错误消息:
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
函数的实现?
解决方案
泛型类型必须是单态的:每个泛型类型必须被解析为具体类型。如果没有约束,编译器就无法知道你想要的具体类型是什么。您必须将泛型类型放入函数中:
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
};
}
推荐阅读
- angular - 具有反应形式的组件的最佳实践是什么?
- php - 您的 SQL 语法有错误 - 但一切似乎都很好
- python - 将扁平字典的元素分组到子列表中
- android - Android 设备 ID
- r - 在 R 中一次根据所有变量的性别分布类型替换 NA
- dart - 如何在 Flutter 中保存图像文件?使用 Image_picker 插件选择的文件
- c++ - 交换链表中的值
- php - 从一页到另一页显示 db 的检查值
- google-assistant-sdk - 分段错误 google assistant sdk
- algorithm - 如何从三个(或 N 个)单独的字符列表中构建一个没有重复字符的字符串?