Search⌘ K
AI Features

Solution Review: Calculate Distance Between Two Points

Understand how to create and use Rust structs by defining a Point structure with x and y coordinates. Learn to implement a function that calculates the distance between two points using arithmetic operations and square root methods. This lesson builds foundational skills in struct manipulation crucial for Rust programming.

We'll cover the following...

Solution:

Rust 1.40.0
#[derive(Debug)] // prints the value of struct using the debug trait
struct Point {
x: i32,
y: i32
}
fn test(point1: Point, point2: Point)-> f32 {
let distance = i32::pow(point1.x - point2.x,2) + i32::pow(point1.y - point2.y,2);
let d = distance as f32;
d.sqrt()
}
fn main(){
let point1 = Point { x: 3, y: 4 };
let point2 = Point { x: 2, y: 3 };
println!("point1:{:?}", point1);
println!("point2:{:?}", point2);
print!("Distance between two points:");
print!("{}", test(point1, point2));
}

Explanation

  • struct Point

    • On line 2, a struct Point is defined which has two items x of type i32 and y of type i32.
  • test function

    • On line 6, a function test is defined which takes parameter point1 and point2 of type Point and returns an f32 type, i.e., the distance between the two points.

    • On line 7, ...