Minimal example to show implementation of traits

This commit is contained in:
Stephan Rehfeld 2026-04-29 17:38:52 +02:00
parent 81205e5b29
commit 28df45da67

View File

@ -1,91 +1,17 @@
//#[derive(Copy, Clone)] #[derive(Copy, Clone)]
struct RGB { struct Vector3 {
red: u8, x: f64,
green: u8, y: f64,
blue: u8, z: f64,
} }
impl RGB { impl Vector3 {
fn new(red: u8, green: u8, blue: u8) -> RGB { fn new(x: f64, y: f64, z: f64) -> Vector3 {
RGB { red, green, blue } Vector3 { x, y, z }
}
fn black() -> RGB {
RGB::new(0, 0, 0)
}
fn white() -> RGB {
RGB::new(255, 255, 255)
}
}
struct Image {
width: usize,
height: usize,
data: Vec<RGB>,
}
impl Image {
fn new(width: usize, height: usize, data: Vec<RGB>) -> 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
} }
} }
fn main() { fn main() {
let image = Image::white_image(640, 480); let vec1 = Vector3::new(1.0, 0.0, 0.0);
let vec2 = Vector3::new(0.0, 1.0, 0.0);
let black = RGB::black();
let c1 = image.get(0, 0);
//let c2 = image.get(1, 1);
let brightest = brighter(c1, &black);
println!("{}", brightest.red);
} }