Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created April 21, 2019 22:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/31b51d7cdbed3fa9890410833745c6fc to your computer and use it in GitHub Desktop.
Save rust-play/31b51d7cdbed3fa9890410833745c6fc to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::ops::Index;
#[derive(Debug)]
struct Image<P> {
width: usize,
pixels: Vec<P>,
}
impl<P: Default + Copy> Image<P> {
/// Create a new image of the given size.
fn new(width: usize, height: usize) -> Image<P> {
Image {
width,
pixels: vec![P::default(); width * height]
}
}
}
impl<P> Index<usize> for Image<P> {
type Output = [P];
fn index(&self, row: usize) -> &Self::Output {
let start = row * self.width;
&self.pixels[start .. start + self.width]
}
}
fn main() {
let image: Image<u32> = Image::new(10, 10);
println!("{:?}", &image[0]);
println!("{:?}", image.index(0));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment