From 28df45da6745bc0e8b1693b420093b4d6b33dfc1 Mon Sep 17 00:00:00 2001 From: Stephan Rehfeld Date: Wed, 29 Apr 2026 17:38:52 +0200 Subject: [PATCH] Minimal example to show implementation of traits --- src/main.rs | 94 ++++++----------------------------------------------- 1 file changed, 10 insertions(+), 84 deletions(-) diff --git a/src/main.rs b/src/main.rs index 8c560b1..c47cf07 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,91 +1,17 @@ -//#[derive(Copy, Clone)] -struct RGB { - red: u8, - green: u8, - blue: u8, +#[derive(Copy, Clone)] +struct Vector3 { + x: f64, + y: f64, + z: f64, } -impl RGB { - fn new(red: u8, green: u8, blue: u8) -> RGB { - RGB { red, green, blue } - } - - fn black() -> RGB { - RGB::new(0, 0, 0) - } - - fn white() -> RGB { - RGB::new(255, 255, 255) - } -} - -struct Image { - width: usize, - height: usize, - data: Vec, -} - -impl Image { - fn new(width: usize, height: usize, data: Vec) -> Image { - if width * height != data.len() { - panic!("Width and height of image does not match amount of data."); - } - - let img = Image { - width, - height, - data, - }; - - img - } - - fn white_image(width: usize, height: usize) -> Image { - let mut data = Vec::new(); - - for i in 0..width * height { - data.push(RGB::white()); - } - - Image::new(width, height, data) - } - - fn get(&self, x: usize, y: usize) -> &RGB { - self.data.get(y * self.width + x).unwrap() - } - - fn get_mut(&mut self, x: usize, y: usize) -> &mut RGB { - self.data.get_mut(y * self.width + x).unwrap() - } -} - -struct Container<'a> { - value: &'a RGB, -} - -impl<'a> Container<'a> { - fn new(value: &RGB) -> Container { - Container { value } - } -} - -fn brighter<'a>(a: &'a RGB, b: &'a RGB) -> &'a RGB { - if a.red / 3 + a.green / 3 + a.blue / 3 > b.red / 3 + b.green / 3 + b.blue / 3 { - a - } else { - b +impl Vector3 { + fn new(x: f64, y: f64, z: f64) -> Vector3 { + Vector3 { x, y, z } } } fn main() { - let image = Image::white_image(640, 480); - - let black = RGB::black(); - - let c1 = image.get(0, 0); - //let c2 = image.get(1, 1); - - let brightest = brighter(c1, &black); - - println!("{}", brightest.red); + let vec1 = Vector3::new(1.0, 0.0, 0.0); + let vec2 = Vector3::new(0.0, 1.0, 0.0); }