Compare commits

..

5 Commits

Author SHA1 Message Date
Stephan Rehfeld
81205e5b29 Example with ownership 2026-04-29 17:35:33 +02:00
Stephan Rehfeld
07d7855f47 CODE DOES NOT Compile
You can't trick the borrow checker, by putting references into another struct
2026-04-22 18:36:00 +02:00
Stephan Rehfeld
352085f8d9 We need lifitime annotation, when struct wants to old a reference. 2026-04-22 18:25:24 +02:00
Stephan Rehfeld
b0e998fb28 Either on mutable borrow or inifite immutable borrows are allowed 2026-04-22 18:12:55 +02:00
Stephan Rehfeld
7a1b0975d2 Example with references and mutable references 2026-04-22 17:59:39 +02:00

View File

@ -1,4 +1,4 @@
#[derive(Copy, Clone)] //#[derive(Copy, Clone)]
struct RGB { struct RGB {
red: u8, red: u8,
green: u8, green: u8,
@ -11,19 +11,11 @@ impl RGB {
} }
fn black() -> RGB { fn black() -> RGB {
RGB { RGB::new(0, 0, 0)
red: 0,
green: 0,
blue: 0,
}
} }
fn white() -> RGB { fn white() -> RGB {
RGB { RGB::new(255, 255, 255)
red: 255,
green: 255,
blue: 255,
}
} }
} }
@ -58,13 +50,42 @@ impl Image {
Image::new(width, height, data) Image::new(width, height, data)
} }
fn get(&self, x: usize, y: usize) -> RGB { fn get(&self, x: usize, y: usize) -> &RGB {
self.data[y * self.width + x] 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 image = Image::white_image(640, 480);
let c = image.get(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);
} }