Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
526 views
in Technique[技术] by (71.8m points)

polymorphism - static vs dynamic heterogeneous collection in rust

I'm brand new to rust so all the lifetimes are probably wrong, please ignore. Assume that the objects are stored somewhere separate. Also that the structs, traits and impls have been filled in with useful stuff. And finally the ordering of the lists doesn't matter.

Fully dynamic version:

trait Shape {}
struct Sphere {}
struct Triangle {}
impl Shape for Sphere{}
impl Shape for Triangle {}

trait Material {}
struct Diffuse {}
struct Glossy {}
impl Material for Diffuse {}
impl Material for Glossy {}

trait Object {}

struct PrimitiveObject<'a> {
    shape: &'a dyn Shape,
    material: &'a dyn Material,
    position: [f32; 3]
}
struct InstancedObject<'a> {
    shape: &'a dyn Shape,
    material: &'a dyn Material,
    positions: Vec<[f32; 3]>
}
impl<'a> Object for PrimitiveObject<'a> {}
impl<'a> Object for InstancedObject<'a> {}

struct Scene<'a> {
    objects: Vec<&'a dyn Object>
}

Slightly more static version

struct Scene<'a> {
    objects_PrimitiveObject: Vec<&'a PrimitiveObject<'a>>,
    objects_InstancedObject: Vec<&'a InstancedObject<'a>>
}

Fully static version

struct PrimitiveObject<'a, Shape: Shape_, Material: Material_> {
    shape: &'a Shape_,
    material: &'a Material_,
    position: [f32; 3]
}
struct InstancedObject<'a, Shape: Shape_, Material: Material_> {
    shape: &'a Shape_,
    material: &'a Material_,
    positions: Vec<[f32; 3]>
}
impl<'a, Shape: Shape_, Material: Material_> Object for PrimitiveObject<'a, Shape_, Material_> {}
impl<'a, Shape: Shape_, Material: Material_>  Object for InstancedObject<'a, Shape_, Material_> {}

struct Scene<'a> {
    objects_PrimitiveObject_Sphere_Diffuse: Vec<&'a PrimitiveObject<'a, Sphere, Diffuse>>,
    objects_PrimitiveObject_Sphere_Glossy: Vec<&'a PrimitiveObject<'a, Sphere, Glossy>>,
    objects_PrimitiveObject_Triangle_Diffuse: Vec<&'a PrimitiveObject<'a, Triangle, Diffuse>>,
    ...
}

Is there a way to make the static versions not by hand, but using macros?

While the static version has exponential growth in the number of type parameters, it seems like it could be faster than dynamic by allowing inlining where it helps. A bunch of empty vectors doesn't seem like a huge cost.

I guess enums are also in the running, but they seem to have a space disadvantage.

question from:https://stackoverflow.com/questions/65903095/static-vs-dynamic-heterogeneous-collection-in-rust

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...