我有一个通用类型的特征.我想定义一个具有满足该特征的属性的结构,我想在该结构中实现一个使用特征内部函数的函数:
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 };
}
Run Code Online (Sandbox Code Playgroud)
(游乐场)
如果我尝试运行此代码,则会收到错误消息:
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
Run Code Online (Sandbox Code Playgroud)
如果我尝试添加泛型类型:
impl<T: Point<I>> Connection<T> {
pub fn is_connected_to(&self, point: T) -> bool {
self.to.id() == point.id()
}
}
Run Code Online (Sandbox Code Playgroud)
然后我收到这个错误:
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`?
Run Code Online (Sandbox Code Playgroud)
如果我尝试定义类型I:
impl<I, T: Point<I>> Connection<T> {
pub fn is_connected_to(&self, point: T) -> bool {
self.to.id() == point.id()
}
}
Run Code Online (Sandbox Code Playgroud)
编译器告诉我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
Run Code Online (Sandbox Code Playgroud)
我该如何声明该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
};
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
333 次 |
| 最近记录: |