rust-lang / rust-lang/libs-team

Add `core::mem::size_of_field!`

Open
#826 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

api-change-proposal
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

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.