我正在学习Rust中的泛型.我创建了一个带有计算其面积的函数的Alzium struct 的简单用例.请考虑下面的例子:
#[derive(Debug)]
struct Trapezium<T> {
a: T,
b: T,
h: T,
area: T,
perimeter: T,
}
fn calc_area<T: std::ops::Add>(a: T, b: T, h: T) -> T {
return (a+b)/2.0/h;
}
fn main() {
let mut t = Trapezium {a: 3.1, b: 6.9, h: 2.5, area: 0.0, perimeter: 0.0};
t.area = calc_area(t.a, t.b, t.h);
println!("t: {:?}", t);
}
我在calc_area
的函数中遇到了问题,因为除以float64
.请在下面找到我的编译错误:
Compiling geometric v0.1.0 (/Users/mabalenk/repo/git/rustup/src/geometric)
error[E0369]: cannot divide `<T as Add>::Output` by `{float}`
--> src/main.rs:12:17
|
12 | return (a+b)/2.0/h;
| -----^--- {float}
| |
| <T as Add>::Output
|
help: consider further restricting the associated type
|
10 | fn calc_area<T: std::ops::Add>(a: T, b: T, h: T) -> T where <T as Add>::Output: Div<f64> {
| ++++++++++++++++++++++++++++++++++
For more information about this error, try `rustc --explain E0369`.
error: could not compile `geometric` (bin "geometric") due to previous error
我对增加where <T as Add>::Output: Div<f64>
条款的建议感到担忧.Div<f64>
不再使其成为通用产品.另外,添加此子句无助于编译代码.而且,它确实使源代码变得非常混乱.
你能推荐一个优雅的"教科书"解决方案,让我的基本例子发挥作用吗?