capypad
0 Tage Serie
rust / beginner
Snippet

Basis-Strukturen und Feldzugriff

Structs gruppieren zusammengehorige Daten. Der impl-Block enthalt Methoden, mit new als Konstruktor. Methodensignaturen nehmen &self um die Instanz zu leihen. distance_to verwendet self und nimmt eine weitere Point-Referenz um die euklidische Distanz zu berechnen.

snippet.rs
rust
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));
}
Erklärung
1
struct Point { x: f64, y: f64 }
Definiert eine Struktur mit zwei f64-Feldern
2
impl Point { fn new(x: f64, y: f64) -> Point
Assoziierte Konstruktor-Funktion
3
fn distance_to(&self, other: &Point) -> f64
Instanzmethode die self und einen anderen Point leiht
4
(dx * dx + dy * dy).sqrt()
Berechnet quadrierte Distanz und nimmt Quadratwurzel
5
p1.distance_to(&p2)
Ruft Methode auf p1 auf, leiht p2