Rust更紧凑的列表初始化方式?

3

我经常需要处理几何数据,在C++中,我通常会这样做:

struct Vertex { vec2;}
vector<Vertex> triangle = {{-1, 0}, {0,1}, {1, 0}};

这相当方便,特别是当您开始拥有更多嵌套类型时,比如向Vertex添加更多字段。

在 Rust 中,初始化程序需要明确指定,因此我会得到像这样的东西:

 let triangle : [Vertex; 3] = [
        Vertex{position : Vec2::new(-0.5, 0.0), color : Vec3::new(1.0, 0.0, 0.0)},
        Vertex{position : Vec2::new(0.0, 0.5), color : Vec3::new(0.0, 1.0, 0.0)},
        Vertex{position : Vec2::new(0.5, 0.0), color : Vec3::new(0.0, 0.0, 1.0)},
    ];

这有点过于繁琐,反复指定相同的字段变得乏味,即使在不太糟糕的情况下,当您拥有位置、法线和UV字段时,它也会变成一团糟。

是否有一种更紧凑的方式初始化列表?


经常使用的宏? - Chayim Friedman
有点hacky,而且不太适用于任意类型的扩展 :\ - Makogan
取决于你如何定义它。 - Chayim Friedman
2个回答

3

您可以简化初始化过程,通常可以通过实现From特性来完成。

之后您的代码可能如下所示

    let triangle : [Vertex; 3] = [
        ([-0.5, 0.0], [1.0, 0.0, 0.0]).into(),
        ([0.0, -0.5], [0.0, 1.0, 0.0]).into(),
        ([0.0, -1.0], [0.0, 1.0, 1.0]).into(),
    ];

点击此处查看完整示例

另一种方法是创建fn new(x: f32, y: f32, c1: f32, c2: f32, c3: f32) -> Vertex

impl Vertex {
    fn new(x: f32, y: f32, c1: f32, c2: f32, c3: f32) -> Vertex {
        Self {
            position: Vec2{x, y},
            color: Vec3{x: c1, y: c2, z: c3}
        }
    }
}
fn main() {
    let triangle : [Vertex; 3] = [
        Vertex::new(0.0, 0.1, 0.2, 0.3, 0.4),
        Vertex::new(0.1, 0.1, 0.2, 0.3, 0.4),
        Vertex::new(0.2, 0.1, 0.2, 0.3, 0.4),
    ];
}

有没有一种自动生成新方法的方式?为每个我想要从元组/列表初始化的结构编写那段代码会有些烦人。 - Makogan

0

这可能对你来说不够简洁,但非常Rust-y的模式是构建器模式。你的代码可能看起来像这样:

let triangle: [Vertex; 3] = [
    Vertex::new().with_position(-0.5, 0.0).with_color(1.0, 0.0, 0.0),
    Vertex::new().with_position(0.0, 0.5).with_color(0.0, 1.0, 0.0),
    Vertex::new().with_position(0.5, 0.0).with_color(0.0, 0.0, 1.0),
];

这个代码短了很多吗?不是。写起来更方便吗?我认为是的,但这当然是主观的。

完整代码


我认为这个代码在可读性方面做得很好(即使还是有些重复)。 - ph_0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接