My class notes have code that implements the HasArea
trait and prints the area, similar to the Rust Book example. The professor's note is as following:
trait HasArea<T> {
fn area(& self) -> T,
}
fn print<T: Display, S: HasArea<T>>(s: &S) {
println!("", s.area()); // println sth must impl Display trait
}
struct Circle {
x: T,
y: T,
r: T,
}
impl <T: Copy + Mul <Output = T>>
HasArea<T> for Circle<T>
{
fn area(&self) -> T {
self.r * self.r
}
}
Comparing that to the Rust Book, which uses shape: T
as input:
trait HasArea {
fn area(&self) -> f64;
}
struct Circle {
x: f64,
y: f64,
radius: f64,
}
impl HasArea for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * (self.radius * self.radius)
}
}
fn print_area<T: HasArea>(shape: T) {
println!("This shape has an area of {}", shape.area());
}
fn main() {
let c = Circle {
x: 0.0f64,
y: 0.0f64,
radius: 1.0f64,
};
print_area(c);
}
I am not sure why the professor uses s: &S
, while the Rust Book uses shape: T
. Can anyone help compare when implementing a generic function, when do we pass a input as x: &T
and when x: T
?