rust / beginner
Snippet
Basic Structs and Field Access
Structs group related data together. The impl block contains methods, with new as a constructor. Method signatures take &self to borrow the instance. distance_to uses self and takes another Point reference to compute Euclidean distance.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
struct Point {x: f64,y: f64,}impl Point {fn new(x: f64, y: f64) -> Point {Point { x, y }}fn distance_to(&self, other: &Point) -> f64 {let dx = self.x - other.x;let dy = self.y - other.y;(dx * dx + dy * dy).sqrt()}}fn main() {let p1 = Point::new(3.0, 4.0);let p2 = Point::new(0.0, 0.0);println!("Distance: {}", p1.distance_to(&p2));}
Breakdown
1
struct Point { x: f64, y: f64 }
Defines a struct with two f64 fields
2
impl Point { fn new(x: f64, y: f64) -> Point
Associated constructor function
3
fn distance_to(&self, other: &Point) -> f64
Instance method taking borrowed self and other point
4
(dx * dx + dy * dy).sqrt()
Computes squared distance and takes square root
5
p1.distance_to(&p2)
Calls method on p1, borrowing p2