简体   繁体   English

Rust 更紧凑的列表初始化?

[英]Rust more compact list initialisation?

I commonly have to work with geometric data, in C++ it was normal for me to do things like this:我通常必须处理几何数据,在 C++ 中,我做这样的事情是很正常的:

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

Which is fairly convenient, especially if you start having more nested types, like adding more fields to Vertex.这相当方便,尤其是当您开始拥有更多嵌套类型时,例如向 Vertex 添加更多字段。

In rust initializers need to be explicit, so i get things like this:在 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)},
    ];

This is a little too much, it becomes tedious to specify the same fields over and over again, and this is not even that bad of a scenario, when you have position, normal and uv fields it becomes a mess.这有点太多了,一遍又一遍地指定相同的字段变得乏味,这甚至不是那么糟糕的场景,当您拥有 position、正常和 uv 字段时,它变得一团糟。

Is there a way to initialise lists in a more compact way?有没有办法以更紧凑的方式初始化列表?

You can simplify initialization, this is usually done by implementing From trait.您可以简化初始化,这通常通过实现From特征来完成。

After that your code may look like之后你的代码可能看起来像

    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(),
    ];

Check a complete example here 在此处查看完整示例

Other way is to create fn new(x: f32, y: f32, c1: f32, c2: f32, c3: f32) -> Vertex :其他方法是创建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),
    ];
}

This may not be terse enough for you, but a very Rust-y pattern is the builder pattern .这对你来说可能不够简洁,但是一个非常 Rust-y 的模式是builder 模式 Your code could look like this:您的代码可能如下所示:

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),
];

Is this a lot shorter?这是不是短了很多? No. Is it more convenient to write?不,写起来更方便吗? I think so, but it's certainly subjective.我想是的,但这肯定是主观的。

Full code 完整代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM