 # Learning how to define and use a trait

Can someone tell me what is wrong with the following code which defines a way to compute the distance between two points? I think it's close to working.

``````fn main() {
struct Point {
x: f64,
y: f64,
}

trait Distance<T> {
fn distanceTo(self: &Self, other: &Self) -> T {}
}

impl Distance<f64> for Point {
fn distanceTo(self: &Point, other: &Point) -> f64 {
let dx = self.x - other.x;
let dy = self.y - other.y;
return (dx.powf(2.0) + dy.powf(2.0)).sqrt();
}
}

let p1 = Point { x: 3.0, y: 4.0 };
let p2 = Point { x: 6.0, y: 8.0 };
let d = p1.distanceTo(&p2);
println!("distance is {}", d);
}

``````

Errors:

``````   Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
--> src/main.rs:8:55
|
7 |     trait Distance<T> {
|                    - this type parameter
8 |         fn distanceTo(self: &Self, other: &Self) -> T {}
|                                                       ^^ expected type parameter `T`, found `()`
|
= note: expected type parameter `T`
found unit type `()`

error: aborting due to previous error

error: could not compile `playground`

``````

Very close. Here's the change:

``````-        fn distanceTo(self: &Self, other: &Self) -> T {}
+        fn distanceTo(self: &Self, other: &Self) -> T;
``````

Trait functions can have default implementations, and when it saw the `{ ... }`, the compiler looked for such a default implementation. To just declare it, use `;`.

2 Likes

Replace the `-> {}` in the trait definition with a semicolon. The trait definition need not define a default implementation.

2 Likes