Indexing a subset of fields

⚓ Rust    📅 2025-10-14    👤 surdeus    👁️ 2      

surdeus

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Indexing a subset of fields

I have a design question involving struct indexing and field level access. I'm trying to store a reference to a field, and/or the field offset(?) itself.
The intention is to be able to associate the field with an intermediate value that is operated on over time, periodically writing back the value. An arbitrary number of these operations are intended to be composed and acting at once, targeting different fields with different update rates, etc. This is used to animate things like positions and colors, but any floating point property is valid.

I'd like to avoid copying the whole struct for each property set. I'm updating some arbitrary subset of fields and that data padding will add up quickly.
I can retrieve the actual struct to write back the data, but I'm having trouble finding a good way to map each value back to it's field in the struct.

This is essentially a domain-specific compressor. I'm using specs to manage entities and compose units of functionality.

My first attempt at a design has resulted in implementing IndexMut and using indexing to associate the values. The cost of a usize per field isn't great, but probably better than cloning the whole struct to update a single property. Buuuuut it's a lot of manual implementation. Ideally I can find a mechanism that is derivable or in the best case a zero cost reference.

My other thought was a proc-macro to generate some kind of serialization/deserialization mechanism. Perhaps there is a clever solution with lambdas I'm missing.
My big goal is to be able to trivially add new structs with the minimum amount of mapping code and/or boilerplate.

Ideally I can just create an array of tuples of references to fields and paired data, and pass that, dereferencing it where I do the work, but that might violate memory safety. This should be threadsafe-ish.

Interested in other people's thoughts and design patterns.

2 posts - 2 participants

Read full topic

🏷️ Rust_feed