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

标签 c++ rust syntax list-initialization

我通常需要处理几何数据,在 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/

相关文章:

java - SQL语句语法错误

c++ - 众所周知,C++ 中的 long long 在精度方面非常糟糕吗?

c++ - 通过 IIS 应用程序池 w3wp.exe 调用 COM DLL 时未调用 DLL_THREAD_ATTACH

c++ - `unsigned long long` 太小不能代表数字?

recursion - Rust 中的基本树和指针

pointers - 我如何在 Rust 中编写这个 C 函数?

rust - 在处理 if/else 中的不兼容类型时如何删除重复?

go - 为什么 Go 使用 ^ 而不是 ~ 来表示一元按位非?

r - 组合取消分类因子变量

c++ - 使用 c++ 和 x86 和 x64 架构访问处理器中断