作者:宝宝2502932575 | 来源:互联网 | 2022-12-09 12:00
我有一个通用类型的特征.我想定义一个具有满足该特征的属性的结构,我想在该结构中实现一个使用特征内部函数的函数:
pub trait Point {
fn id(&self) -> I;
}
pub struct Connection {
pub to: T,
}
impl Connection {
pub fn is_connected_to(&self, point: T) -> bool {
self.to.id() == point.id()
}
}
pub fn main() {
struct SimplePoint;
impl Point 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 Connection {
| ^^^^^ expected 1 type argument
如果我尝试添加泛型类型:
impl> Connection {
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> Connection {
| ^ did you mean `T`?
如果我尝试定义类型I
:
impl> Connection {
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> Connection {
| ^ unconstrained type parameter
我该如何声明该is_connected_to
函数的实现?
1> French Boiet..:
泛型类型必须是单形的:每个泛型类型必须作为具体类型解析.如果没有约束,编译器就无法知道您想要的具体类型.您必须将泛型类型放在函数中:
pub trait Point {
fn id(&self) -> I;
}
pub struct Connection {
pub to: T
}
impl Connection {
pub fn is_connected_to(&self, point: T) -> bool
where
T: Point
{
self.to.id() == point.id()
}
}
pub fn main() {
struct SimplePoint;
impl Point for SimplePoint{
fn id(&self) -> char { return 'A' }
}
let a = SimplePoint {};
let cOnn= Connection {
to: a
};
}