Rust Program: Calculate distance between Points
Rust Structs and Enums: Exercise-3 with Solution
Write a Rust program that defines a struct Point with fields x and y. Now write a function to calculate the distance between two points.
Sample Solution:
Rust Code:
use std::f64;
// Define a struct named 'Point' with fields 'x' and 'y'
#[derive(Debug)]
struct Point {
x: f64,
y: f64,
}
// Implementation block for the 'Point' struct
impl Point {
// Define a method named 'distance_to' that calculates the distance between two points
fn distance_to(&self, other: &Point) -> f64 {
// Calculate the distance using the Euclidean distance formula
((self.x - other.x).powi(2) + (self.y - other.y).powi(2)).sqrt()
}
}
fn main() {
// Create two points
let point1 = Point { x: 1.0, y: 2.0 };
let point2 = Point { x: 4.0, y: 6.0 };
// Calculate the distance between the two points using the 'distance_to' method
let distance = point1.distance_to(&point2);
// Print the calculated distance
println!("Distance between the points: {:.2}", distance);
}
Output:
Distance between the points: 5.00
Explanation:
Here is a brief explanation of the above Rust code:
- struct Point { ... }: Defines a struct named "Point" with two fields 'x' and 'y', both of type f64. This struct represents a point in a 2D Cartesian coordinate system.
- impl Point { ... }: Begins an implementation block for the "Point" struct.
- fn distance_to(&self, other: &Point) -> f64 { ... }: Defines a method named 'distance_to' that takes a reference to 'self' (an instance of "Point") and a reference to another "Point" instance (other) as parameters. It returns the calculated distance between the two points as a 'f64'.
- Inside the method:
- The distance between two points is calculated using the Euclidean distance formula: √((x₂ - x₁)² + (y₂ - y₁)²).
- In the main function,
- Two "Point" instances ('point1' and 'point2') are created with specific coordinates.
- The "distance_to()" method is called on 'point1' with a reference to 'point2' to calculate the distance between them.
- The calculated distance is printed to the console.
Rust Code Editor:
Previous: Rust Program: Enum Direction.
Next: Rust Program: Implement Enum for Geometric shapes.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/rust/basic/rust-structs-and-enums-exercise-3.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics