Image example to show Ownership
This commit is contained in:
parent
bd260f1769
commit
12a54c42da
81
src/main.rs
81
src/main.rs
@ -1,37 +1,70 @@
|
||||
struct Vector3 {
|
||||
x: f32,
|
||||
y: f32,
|
||||
z: f32,
|
||||
#[derive(Copy, Clone)]
|
||||
struct RGB {
|
||||
red: u8,
|
||||
green: u8,
|
||||
blue: u8,
|
||||
}
|
||||
|
||||
impl Vector3 {
|
||||
pub fn new(x: f32, y: f32, z: f32) -> Vector3 {
|
||||
Vector3 { x, y, z }
|
||||
impl RGB {
|
||||
fn new(red: u8, green: u8, blue: u8) -> RGB {
|
||||
RGB { red, green, blue }
|
||||
}
|
||||
|
||||
fn black() -> RGB {
|
||||
RGB {
|
||||
red: 0,
|
||||
green: 0,
|
||||
blue: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn print(vec: Vector3) -> Vector3 {
|
||||
println!("Vector3( x = {}, y = {}, z = {})", vec.x, vec.y, vec.z);
|
||||
|
||||
vec
|
||||
fn white() -> RGB {
|
||||
RGB {
|
||||
red: 255,
|
||||
green: 255,
|
||||
blue: 255,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Vector3 {
|
||||
fn drop(&mut self) {
|
||||
println!("Vector3 was dropped!");
|
||||
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[y * self.width + x]
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut vec = Vector3::new(1.0, 0.0, 0.0);
|
||||
let image = Image::white_image(640, 480);
|
||||
|
||||
/*
|
||||
println!("Calling print");
|
||||
let vec2 = print(vec);
|
||||
println!("Calling print returned");
|
||||
*/
|
||||
|
||||
let vec2 = vec;
|
||||
|
||||
vec.y = 2.0;
|
||||
let c = image.get(0, 0);
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user