Macro repr_offset::OFF
source · macro_rules! OFF { ( $(:: $(@$leading:tt@)? )? $first:ident $(:: $trailing:ident)* ; $($fields:tt).+ ) => { ... }; ($type:ty; $($fields:tt).+ ) => { ... }; }
Expand description
Gets the FieldOffset
for the passed in type and (possibly nested) field.
This macro allows accessing private fields, following the normal Rust rules around privacy.
This macro doesn’t allow accessing fields from type parameters in generic functions,
for that you can use PUB_OFF
,
but it can only get the FieldOffset
for public fields.
§Type Argument
The type parameter can be passed as either:
-
The path to the type (including the type name)
-
A type with generic arguments
§Caveats with path argument
With the path way of passing the type, if the type has all type parameters defaulted or is otherwise generic, there can be type inference issues.
To fix type inference issues with defaulted types,
you can write <>
(eg: OFF!(for_examples::ReprC<>; a.b)
).
If a generic type is passed, and its arguments can be inferred from context, it’s only necessary to specify the type of the accessed field, otherwise you need to write the full type.
§Example
use repr_offset::{
for_examples::ReprC,
OFF,
FieldOffset, ROExtAcc,
};
let this = ReprC {a: 3u8, b: 5u8, c: 8u8, d: 13u8};
// Passing the type as a path
assert_eq!(OFF!(ReprC; a).get(&this), &this.a);
// Passing the type as a type
assert_eq!(OFF!(ReprC<_, _, _, _>; b).get(&this), &this.b);
// Passing the type as a path
assert_eq!(this.f_get(OFF!(ReprC; c)), &this.c);
// Passing the type as a type
assert_eq!(this.f_get(OFF!(ReprC<_, _, _, _>; d)), &this.d);