Rust 如何通过泛型类型获取数组结构(SOA)中的值?
我正在寻找您对一段代码的反馈/建议 基本上,我有这样一个SOA:Rust 如何通过泛型类型获取数组结构(SOA)中的值?,rust,game-development,entity-component-system,Rust,Game Development,Entity Component System,我正在寻找您对一段代码的反馈/建议 基本上,我有这样一个SOA: struct Entities { pub meshes: FakeArena<Mesh>, pub lights: FakeArena<Light>, } 这很好用。我将泛型类型向下转换为具体类型,然后再次转换为泛型类型,但这看起来很奇怪和棘手 也许我遗漏了什么,或者你对此有更好的想法;你会怎么做?:) 这里不需要任何动态调度,简单的静态调度就足够了 创建一个引用容器结构的特征。每个组
struct Entities {
pub meshes: FakeArena<Mesh>,
pub lights: FakeArena<Light>,
}
这很好用。我将泛型类型向下转换为具体类型,然后再次转换为泛型类型,但这看起来很奇怪和棘手
也许我遗漏了什么,或者你对此有更好的想法;你会怎么做?:) 这里不需要任何动态调度,简单的静态调度就足够了 创建一个引用容器结构的特征。每个组件类型都实现此特性并选择容器的适当字段。然后,在你的
get
方法中要求特质并使用它:
struct Mesh;
struct Light;
struct Entities {
meshes: Vec<Mesh>,
lights: Vec<Light>,
}
trait Example {
fn get_in<'a>(&self, entities: &'a Entities) -> &'a Self;
}
impl Example for Mesh {
fn get_in<'a>(&self, entities: &'a Entities) -> &'a Self {
&entities.meshes[0]
}
}
impl Example for Light {
fn get_in<'a>(&self, entities: &'a Entities) -> &'a Self {
&entities.lights[0]
}
}
impl Entities {
fn get<T: Example>(&self, handle: T) -> &T {
handle.get_in(self)
}
}
fn example(entities: &Entities) {
let m = entities.get(Mesh);
let l = entities.get(Light);
}
struct网格;
结构光;
结构实体{
主席:Vec,,
灯光:Vec,
}
特征示例{
进入自我;
}
网格的impl示例{
fn进入自我{
&实体.网格[0]
}
}
光的impl示例{
fn进入自我{
&实体.灯光[0]
}
}
impl实体{
fn获取(&self,句柄:T)->&T{
处理。让你进去(自己)
}
}
fn示例(实体:&实体){
设m=entities.get(Mesh);
设l=entities.get(Light);
}
这里不需要任何动态调度,简单的静态调度就足够了
创建一个引用容器结构的特征。每个组件类型都实现此特性并选择容器的适当字段。然后,在你的get
方法中要求特质并使用它:
struct Mesh;
struct Light;
struct Entities {
meshes: Vec<Mesh>,
lights: Vec<Light>,
}
trait Example {
fn get_in<'a>(&self, entities: &'a Entities) -> &'a Self;
}
impl Example for Mesh {
fn get_in<'a>(&self, entities: &'a Entities) -> &'a Self {
&entities.meshes[0]
}
}
impl Example for Light {
fn get_in<'a>(&self, entities: &'a Entities) -> &'a Self {
&entities.lights[0]
}
}
impl Entities {
fn get<T: Example>(&self, handle: T) -> &T {
handle.get_in(self)
}
}
fn example(entities: &Entities) {
let m = entities.get(Mesh);
let l = entities.get(Light);
}
struct网格;
结构光;
结构实体{
主席:Vec,,
灯光:Vec,
}
特征示例{
进入自我;
}
网格的impl示例{
fn进入自我{
&实体.网格[0]
}
}
光的impl示例{
fn进入自我{
&实体.灯光[0]
}
}
impl实体{
fn获取(&self,句柄:T)->&T{
处理。让你进去(自己)
}
}
fn示例(实体:&实体){
设m=entities.get(Mesh);
设l=entities.get(Light);
}
哦,你的方式好多了。谢谢哦,你的方式好多了。谢谢