macro_rules! field {
($s:ident . $f:ident) => { ... };
(& $s:ident . $f:ident) => { ... };
(&mut $s:ident . $f:ident) => { ... };
}Expand description
Access a field of an anonymous struct object.
use structz::*;
let mut person = stru! {
name: "John Doe",
age: 26,
tags: vec!["developer", "rustacean"],
};
// immutable borrow
assert_eq!(field!(&person.name), &"John Doe");
// mutable borrow
*field!(&mut person.age) += 1;
assert_eq!(field!(&person.age), &27);
// consume the struct and get the field value
let tags = field!(person.tags);
assert_eq!(tags, vec!["developer", "rustacean"]);
// `person` cannot be used anymore.Unlike the built-in member access operator ., structz uses some type deduction magic
to achieve access to the specified field. Therefore, it is not smart enough:
it cannot move a value of certain field out while keeping other fields remain valid,
and it also cannot avoid consume the entire struct object while moving a value that
implements Copy out.
However, if all fields implement Copy, then the anonymous struct will also implement Copy:
use structz::*;
let pos = stru! {
x: 300,
y: 480,
marker: "Block",
};
assert_eq!(field!(pos.x), 300);
assert_eq!(field!(pos.y), 480);
assert_eq!(field!(pos.marker), "Block");