如何有效地使用元组结构作为新类型?

时间:2016-11-12 22:06:00

标签: rust

我需要在网格上表示2D坐标。我知道«newtype»模式有助于避免宽度和高度之间的错误。

#[derive(Copy, Clone, Debug)]
pub struct Width(u8);
#[derive(Copy, Clone, Debug)]
pub struct Height(u8);

#[derive(Copy, Clone, Debug)]
pub struct Location {
    pub x: Width,
    pub y: Height,
}

我真的很喜欢这种使用类型系统的模式,以避免在功能参数中无意中交换宽度和高度等错误。

然而,这种方法增加了我的代码的冗长;我最终解构了很多内容来访问内部数据,因为我无法使用我的newtype值:

let Width(w) = width;
let Height(h) = height;

for a in 0..h {
    for b in 0..w {
        //DO SOMETHING HERE
    }
}

let Width(w) = width;
let Height(h) = height;
let mut map = vec![vec![0; w as usize]; h as usize];

我发现如何使用AddSub特征轻松地使用算术运算符和我的newtypes(即使它也有冗长的负担)我想知道是否有特征我可以在我的newtype上实现,以便能够在范围内使用它或将其作为usize进行投放。

更好的是,有没有办法告诉编译器我希望我的newtype与其内容完全一样,而不需要自己手动实现每个特征?这样的事情可能是:

#[derive(everything_from_inner)]
struct Height(u8)

0 个答案:

没有答案