我是Rust的新手,还在学习。我有点困惑,为什么当我编译这段代码时它会失败。我在我的Linux开发机器上使用Cargo构建它。
extern crate image;
extern crate rand;
use image::{ImageBuffer, Rgb};
use rand::Rng;
struct ImageCanvas {
image: image::ImageBuffer,
WIDTH: i32,
HEIGHT: i32,
xPosition: i32,
yPosition: i32
}
impl ImageCanvas {
pub fn new(width: i32, height: i32) -> ImageCanvas {
// create a new instance of an ImagePen.
ImageCanvas{
image: ImageBuffer::<Rgb<u8>>::new(width, height),
WIDTH: width,
HEIGHT: height,
xPosition: 0,
yPosition: 0
}
}
pub fn paint(&self, x: i32, y: i32, rgb: i32){
self.xPosition = x;
self.yPosition = y;
//RGB should be an array.
self.image.get_pixel_mut(self.xPosition, self.yPosition).data = rgb;
}
}
fn main() {
let canvas = ImageCanvas::new(50, 50);
canvas.paint(1, 1, [rand::thread_rng().gen_range(1, 255),
rand::thread_rng().gen_range(1, 255),
rand::thread_rng().gen_range(1, 255)]);
canvas.image.save("yay.png").unwrap();
}错误:
src/main.rs:9:9: 9:27 error: wrong number of type arguments: expected 2, found 0 [E0243]
src/main.rs:9 image: image::ImageBuffer,
^~~~~~~~~~~~~~~~~~
src/main.rs:9:9: 9:27 help: run `rustc --explain E0243` to see a detailed explanation
error: aborting due to previous error我不确定为什么它会给我这个错误。我已经搜索过了,但我没有看到任何其他关于像我这样的菜鸟不理解Rust的OOD的帖子。
发布于 2015-08-07 00:16:29
image::ImageBuffer是一个参数化的结构:
pub struct ImageBuffer<P: Pixel, Container> {
// some fields omitted
}因此,您必须在struct ImageCanvas中提供这些参数。
就像这样
struct ImageCanvas<P: Pixel, Container> {
image: image::ImageBuffer<P, Container>,
WIDTH: i32,
HEIGHT: i32,
xPosition: i32,
yPosition: i32
}或
struct ImageCanvas {
image: image::ImageBuffer<RGB<u8>, Vec<RGB<u8>>>,
WIDTH: i32,
HEIGHT: i32,
xPosition: i32,
yPosition: i32
}发布于 2015-08-07 00:33:00
您实际上正在使用RGB图像,那么为什么不使用专门的版本呢
extern crate image;
extern crate rand;
use image::{RgbImage, Rgb};
use rand::Rng;
// Had to change all of the `i32` to `u32`. I agree, `i32` makes more sense.
struct ImageCanvas {
image: image::RgbImage, // image::ImageBuffer<Rgb<u8>>,
WIDTH: u32,
HEIGHT: u32,
xPosition: u32,
yPosition: u32
}
impl ImageCanvas {
pub fn new(width: u32, height: u32) -> ImageCanvas {
// create a new instance of an ImagePen.
ImageCanvas{
image: RgbImage::new(width, height), //ImageBuffer::<Rgb<u8>>::new(width, height),
WIDTH: width,
HEIGHT: height,
xPosition: 0,
yPosition: 0
}
}
// RGB _IS_ an array
// note the need for `mut`
pub fn paint(&mut self, x: u32, y: u32, rgb: [u8;3]){
self.xPosition = x;
self.yPosition = y;
self.image.get_pixel_mut(self.xPosition, self.yPosition).data = rgb;
}
}
fn main() {
// `mut` here too
let mut canvas = ImageCanvas::new(50, 50);
canvas.paint(1, 1, [rand::thread_rng().gen_range(1, 255),
rand::thread_rng().gen_range(1, 255),
rand::thread_rng().gen_range(1, 255)]);
canvas.image.save("yay.png").unwrap();
}https://stackoverflow.com/questions/31860718
复制相似问题