> module
std::reflect
runtime reflection and binary layout
std::reflect inspects values at runtime: it lists fields and methods, reads and writes fields by name, and calls methods by name. It works on Xur structs and enum variants, records, tuples, native objects and built-in values.
Its Layout type says where a struct's fields sit in memory, for reading and writing binary data. std::reflect::func inspects functions.
> functions
Calls the method name on value with args and returns its result.
The names of value's fields: numbers ("0", "1", ...) for tuples and tuple structs, and an empty list for values without fields.
The layout of the type argument, called as reflect::layout::<T>(). T must be a struct.
The names of the methods of value's type. The to_bytes and byte_size methods every struct has are not listed.
Returns a copy of value with one field changed; value itself is unchanged.
The name of value's type, such as "Point", "Shape::Circle" or "list".
> types
Building methods return a new layout; the original is unchanged.
A struct's layout. Layouts never change once built, so they are shared.
Sets the byte order of integer and float fields (little-endian by default).
Adds a field of a primitive type, given as a type (u16) or a name ("u16"): u8–u64, i8–i64, usize, isize, f32, f64 or bool. A duplicate name is a runtime error.
Like field, but at an explicit byte offset.
layout.is_big_endian() -> boolWhether fields are big-endian.
Sets the byte order of integer and float fields (little-endian by default).
The byte offset of the field name; a missing field is a runtime error.
Reads a value from data at offset. Returns Err if there are too few bytes.
A one-line description, such as Point (size 16, align 8) { x: i64 @ 0, y: i64 @ 8 }.
> layouts
A layout comes from a struct's type and attributes, or is built at runtime. A layout built at runtime reads as a record; one from a struct reads as that struct.
> struct attributes
// C layout (default)
// no padding
8 // minimum alignment
// byte order (Little by default)
8 // explicit field offset
16 // fixed byte count (for bytes fields)> examples
use std::reflect;
use std::reflect::func;
use std::io;
struct Point {
x: i64
y: i64
}
fn add(a: i64, b: i64) -> i64 {
a + b
}
fn main() -> Result<()> {
let p = Point { x: 1, y: 2 };
io::println("fields: {}", reflect::fields(p)); // ["x", "y"]
io::println("x = {}", reflect::get(p, "x")); // 1
let layout = reflect::layout::<Point>();
io::println("{}", layout.to_string());
let data = layout.to_bytes(p);
let p2 = layout.from_bytes(data)?;
io::println("round-trip: {}", p2);
io::println("{}({})", func::name(add), func::param_names(add));
Ok(())
}