Minimal example to show implementation of traits
This commit is contained in:
parent
81205e5b29
commit
28df45da67
94
src/main.rs
94
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<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
|
||||
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);
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user