How do I fix “wrong number of type arguments” whil

2019-03-02 05:39发布

问题:

I'm trying to implement a method:

struct Point<T> {
    x: T,
    y: T,
}

struct Line<T> {
    start: Point<T>,
    end: Point<T>,
}

impl Line {
    fn length(&self) -> f64 {
        let dx: f64 = self.start.x - self.end.x;
        let dy: f64 = self.start.y - self.end.y;
        (dx * dx + dy * dy).sqrt()
    }
}

fn main() {
    let point_start: Point<f64> = Point { x: 1.4, y: 1.24 };
    let point_end: Point<f64> = Point { x: 20.4, y: 30.64 };

    let line_a: Line<f64> = Line {
        start: point_start,
        end: point_end,
    };
    println!("length of line_a = {}", line_a.length());
}

I'm getting this error:

error[E0243]: wrong number of type arguments: expected 1, found 0
  --> src/main.rs:11:6
   |
11 | impl Line {
   |      ^^^^ expected 1 type argument

What is causing this problem?

回答1:

You need to add a type parameter to the impl:

impl Line<f64> {
    fn length(&self) -> f64 {
        let dx: f64 = self.start.x - self.end.x;
        let dy: f64 = self.start.y - self.end.y;
        (dx * dx + dy * dy).sqrt()
    }
}