【问题标题】:How can I implement a smart constructor for a struct with reference fields?如何为具有引用字段的结构实现智能构造函数?
【发布时间】:2022-08-17 07:07:12
【问题描述】:

背景

我正在做wgpu tutorial。 在早期的课程中,有the following code

    let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
        label: Some(\"Render Pass\"),
        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
            view: &view,
            resolve_target: None,
            ops: wgpu::Operations {
                load: wgpu::LoadOp::Clear(wgpu::Color {
                    r: 0.1,
                    g: 0.2,
                    b: 0.3,
                    a: 1.0,
                }),
                store: true,
            },
        })],
        depth_stencil_attachment: None,
    });

由于大部分 RenderPassDescriptor 结构是样板文件,我想将 RenderPassDescriptor 的创建分解到另一个函数中。我试图创建这样的函数:

pub fn make_render_pass_descriptor(view: &wgpu::TextureView, clear_color: wgpu::Color) -> wgpu::RenderPassDescriptor {
    wgpu::RenderPassDescriptor {
        label: Some(\"Render Pass\"),
        color_attachments: &[
            Some(wgpu::RenderPassColorAttachment {
                view: view,
                resolve_target: None,
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Clear(clear_color),
                    store: true,
                },
            })
        ],
        depth_stencil_attachment: None,
    }
}

这将让我用以下代码替换原始代码:

    let descriptor      = make_render_pass_descriptor(view, clear_color);
    let mut render_pass = encoder.begin_render_pass(&descriptor);

问题

不幸的是,由于color_attachments 设置为临时常量&[...],我收到以下错误:

error[E0515]: cannot return value referencing temporary value

问题

理想情况下,我想告诉编译器将临时常量的生命周期延长到调用函数的生命周期。 这可能吗?如果不是,那么将RenderPassDescriptor 的创建分解出来的惯用方法是什么?

  • 这是不可能的(没有宏),我认为惯用的方法就是保持原样,也许将整个调用放在一个函数中。

标签: rust


【解决方案1】:

wgpu“描述符”基本上只是函数的复杂命名参数。将它们与函数调用放在一起,你不会有这些借贷问题:

pub fn begin_render_pass<'p>(
    encoder: &'p mut wgpu::CommandEncoder,
    view: &wgpu::TextureView,
    clear_color: wgpu::Color,
) -> wgpu::RenderPass<'p> {
    encoder.begin_render_pass(wgpu::RenderPassDescriptor {
        label: Some("Render Pass"),
        color_attachments: &[
            Some(wgpu::RenderPassColorAttachment {
                view: view,
                resolve_target: None,
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Clear(clear_color),
                    store: true,
                },
            })
        ],
        depth_stencil_attachment: None,
    })
}

【讨论】:

    猜你喜欢
    • 2014-02-10
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    相关资源
    最近更新 更多