gpt4 book ai didi

c++ - Rust 更紧凑的列表初始化?

转载 作者:行者123 更新时间:2023-12-05 03:19:45 26 4
gpt4 key购买 nike

我通常需要处理几何数据,在 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 字段时,它会变得一团糟。

有没有办法以更紧凑的方式初始化列表?

最佳答案

您可以简化初始化,这通常通过实现 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(),
];

Check a complete example here

另一种方法是创建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),
];
}

关于c++ - Rust 更紧凑的列表初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73359078/

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