find the midpoint between two points in rust

To find the midpoint between two points in Rust, you can use the following code:

main.rs
struct Point {
    x: f64,
    y: f64,
}

impl Point {
    fn midpoint(&self, other: &Point) -> Point {
        Point {
            x: (self.x + other.x) / 2.0,
            y: (self.y + other.y) / 2.0,
        }
    }
}

fn main() {
    let p1 = Point { x: 0.0, y: 0.0 };
    let p2 = Point { x: 2.0, y: 4.0 };
    let mid = p1.midpoint(&p2);
    println!("Midpoint: ({}, {})", mid.x, mid.y);
}
395 chars
21 lines

Here, we define a Point struct with x and y coordinates, and an implementation that defines a midpoint method that returns a new Point at the midpoint between itself and another Point.

In the main function, we create two points p1 and p2, find their midpoint using the midpoint method, and print the result.

gistlibby LogSnag