我是Rust的新手,来自C ++背景,我在通用特性中实现默认行为时遇到了一些麻烦。通用Rectangle
特征的以下样本特征(适用于i32
和f32
):
trait Rectangle<T: PartialOrd> {
fn left(&self) -> f32;
fn top(&self) -> f32;
fn right(&self) -> f32;
fn bottom(&self) -> f32;
fn x(&self) -> f32 { self.left() }
fn y(&self) -> f32 { self.top() }
fn width(&self) -> f32 { self.right() - self.left() }
fn height(&self) -> f32 { self.bottom() - self.top() }
fn is_empty(&self) -> bool {
self.left() >= self.right() || self.top() >= self.bottom()
}
fn set_ltrb(&mut self, l: T, t: T, r: T, b: T);
fn set_xywh(&mut self, x: T, y: T, w: T, h: T);
fn set_wh(&mut self, w: T, h: T);
fn offset(&mut self, dx: T, dy: T);
fn intersects(&self, other: &Rectangle<T>) -> bool {
let l = self.left().max(other.left());
let t = self.top().max(other.top());
let r = self.right().max(other.right());
let b = self.bottom().max(other.bottom());
l < r && t < b
}
fn intersect(&mut self, other: &Rectangle<T>) -> bool {
let l = self.left().max(other.left());
let t = self.top().max(other.top());
let r = self.right().max(other.right());
let b = self.bottom().max(other.bottom());
if l < r && t < b {
self.set_ltrb(l,t,r,b); // This is the offending line
true
} else {
false
}
}
}
pub struct Rect<T> {
pub left: T,
pub top: T,
pub right: T,
pub bottom: T,
}
pub type IRect = Rect<i32>;
pub type FRect = Rect<f32>;
导致出现此错误消息:
Compiling dinky v0.1.0 (file:///home/menozzi/Desktop/projects/dinky)
src/rect.rs:37:27: 37:28 error: mismatched types:
expected `T`,
found `f32`
(expected type parameter,
found f32) [E0308]
src/rect.rs:37 self.set_ltrb(l,t,r,b);
^
src/rect.rs:37:27: 37:28 help: run `rustc --explain E0308` to see a detailed explanation
src/rect.rs:37:29: 37:30 error: mismatched types:
expected `T`,
found `f32`
(expected type parameter,
found f32) [E0308]
src/rect.rs:37 self.set_ltrb(l,t,r,b);
^
src/rect.rs:37:29: 37:30 help: run `rustc --explain E0308` to see a detailed explanation
src/rect.rs:37:31: 37:32 error: mismatched types:
expected `T`,
found `f32`
(expected type parameter,
found f32) [E0308]
src/rect.rs:37 self.set_ltrb(l,t,r,b);
^
src/rect.rs:37:31: 37:32 help: run `rustc --explain E0308` to see a detailed explanation
src/rect.rs:37:33: 37:34 error: mismatched types:
expected `T`,
found `f32`
(expected type parameter,
found f32) [E0308]
src/rect.rs:37 self.set_ltrb(l,t,r,b);
^
src/rect.rs:37:33: 37:34 help: run `rustc --explain E0308` to see a detailed explanation
error: aborting due to 4 previous errors
Could not compile `dinky`.
To learn more, run the command again with --verbose.
知道为什么这种类型不匹配?