Example with references and mutable references

This commit is contained in:
Stephan Rehfeld 2026-04-22 17:59:39 +02:00
parent 12a54c42da
commit 7a1b0975d2

View File

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