gpt4 book ai didi

arrays - 如何在 Rust 的构造函数中创建数组

转载 作者:行者123 更新时间:2023-11-29 08:10:07 24 4
gpt4 key购买 nike

出于学习目的,我想将一些代码从 C 迁移到 Rust,并使我的学习库更加多语言。

问题是我知道有一种方法可以将 C 库集成到 Rust 中。这样我可以在 Rust 中使用 calloc 来创建我的数组,其范围在运行时指定。

但是 我不想在这里使用 calloc - 我想看看 Rust 的方式。但我真的不想使用 vec! ;我之前遇到过一些愚蠢的问题,所以我暂时不想使用它。

代码如下:

pub struct Canvas {
width: usize,
height: usize,
array: [char], // I want to declare its type but not its size yet
}

impl Canvas{
pub fn new (&self, width: usize, height: usize) -> Canvas {
Canvas {
width: width,
height: height,
array: calloc(width, height), // alternative to calloc ? }
}
}

我希望我的问题仍然符合 Rust 代码方式。

最佳答案

i want to access that array with coordinates style

是这样的吗?

pub struct Canvas {
width: usize,
height: usize,
data: Vec<u8>,
}

impl Canvas {
pub fn new(width: usize, height: usize) -> Canvas {
Canvas {
width: width,
height: height,
data: vec![0; width*height],
}
}

fn coords_to_index(&self, x: usize, y: usize) -> Result<usize, &'static str> {
if x<self.width && y<self.height {
Ok(x+y*self.width)
} else {
Err("Coordinates are out of bounds")
}
}

pub fn get(&self, x: usize, y: usize) -> Result<u8, &'static str> {
self.coords_to_index(x, y).map(|index| self.data[index])
}

pub fn set(&mut self, x: usize, y: usize, new_value: u8) -> Result<(), &'static str>{
self.coords_to_index(x, y).map(|index| {self.data[index]=new_value;})
}
}

fn main() {
let mut canvas = Canvas::new(100, 100);
println!("{:?}", canvas.get(50, 50)); // Ok(0)
println!("{:?}", canvas.get(101, 50)); // Err("Coordinates are out of bounds")
println!("{:?}", canvas.set(50, 50, 128)); // Ok(())
println!("{:?}", canvas.set(101, 50, 128)); // Err("Coordinates are out of bounds")
println!("{:?}", canvas.get(50, 50)); // Ok(128)
}

关于arrays - 如何在 Rust 的构造函数中创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36028001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com