Listings Lankes, Breitbart/Rust


Listing 1: Beispiel für das Verwenden von Traits
trait Vehicle {
    fn get_speed(&self) -> f32;
    fn get_consumption(&self) -> f32;
}

struct Car {
    speed: f32,
    consumption: f32,
}

impl Vehicle for Car {
    fn get_speed(&self) -> f32 {
      self.speed
    }

    fn get_consumption(&self) -> f32 {
      self.consumption
    }
}

-------

Listing 2: Einen Vektor mit Trait Objects erzeugen
let mut vehicles: Vec<Box<dyn Vehicle>> = Vec::new();

vehicles.push(Box::new(Car::new()));
vehicles.push(Box::new(Truck::new()));

for v in vehicles {
    let speed = v.get_speed()

    // do something with speed
}

-------

Listing 3: Beispiel einer ungültigen Referenz in C++
std::vector<std::string>* x = nullptr;

{
    std::vector<std::string> z;

    z.push_back("Hello World!");
    x = &z;
}

std::cout << (*x)[0] << std::endl;

-------

Listing 4: Versuch zum Erzeugen einer ungültigen Referenz in Rust
let x;

{
    let z = vec!("Hello World!");

    x = &z;
}

println!("{}", x[0]);

-------

Listing 5: Objekte ausleihen
let mut x = vec!("Hello World!");

{
    let z = &mut x;
    // Do something with z...
}

println!("{}", x[0]);

-------

Listing 6: Generische Typen verwenden
struct Vector<T> {
    x: T,
    y: T,
    z: T,
}

fn do_something<T>(v: Vector<T>) {
    // do something with the vector v
}

-------

Listing 7: Fehlerbehandlung in Rust
enum MathError {
    DivisionByZero,
    NonPositiveLogarithm,
    NegativeSquareRoot,
}

fn div(x: f64, y: f64) -> Result<f64, MathError> {
    if y == 0.0 {
      Err(MathError::DivisionByZero)
    } else {
      Ok(x / y)
    }
}

-------

Listing 8: Auswerten des Rückgabewertes
match div(42.0, 2.0) {
    Err(why) => panic!("math error"),
    Ok(result) => println!("result {}", result);
}

let result = div(24.0, 0.0).unwrap();
println!("result {}", result);

-------

Listing 9: Optionale Rückgabewerte verwenden
fn find(s1: String, s2: String) -> Option<usize> {
    ...
}

match find("Heise", "eise") {
    Some(i) => println!("Found substring at position {}", i),
    None => println!("Unable to found substring"),
}