rust-lang / rust-lang/libs-team
Add `core::mem::size_of_field!`
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 178
- Forks
- 28
- Avg merge
- 15m
- Merged PRs (30d)
- 1
Description
Proposal
Problem statement
There is currently no standard way to compute the size of a field in a struct without instantiating it. I propose to add core::mem::size_of_field! that works akin to the core::mem::offset_of! macro.
Motivating examples or use cases
This is useful for me when using bindgen and checking that the layout of a C struct matches the layout of a Rust struct exactly.
I believe that the most straightforward way to do it currently is:
fn get_field_size<F: FnOnce(T) -> U, T, U>(_f: F) -> usize {
core::mem::size_of::<U>()
}
get_field_size(|s: MyStruct| s.field);
This could simply be a macro:
size_of_field!(MyStruct, field);
Solution sketch
pub macro size_of_field($Container:ty, $($fields:expr)+ $(,)?) { .. }
Alternatives
See the above get_field_size.
Links and related work
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reading the existing core::mem::offset_of! macro and the linked discussions about field-size APIs. Compare the proposed syntax and behavior with the stated bindgen and C-layout use case, then define representative struct cases and tests that establish what successful support looks like.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- backend-api-design
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100