structz
Anonymous struct implementation in rust.
Overview
Install
Create & access
use *;
let age = 26;
let mut person = stru! ;
// immutable borrow
assert_eq!;
// mutable borrow
*field! += 1;
assert_eq!;
// consume the struct and get the field value
let tags = field!;
assert_eq!;
// `person` cannot be used anymore.
NOTE: anonymous structs with the same fields but different field orders are considered structs of the same type.
use *;
let rect1 = stru! ;
let rect2 = stru! ;
assert_eq!;
As argument
use *;
let person = stru! ;
print_person;
A better way is to use the named_args
macro which helps you unpack the struct:
use *;
let person = stru! ;
print_person;
With the subseq()
method by tuplez,
you can get a sub-struct of the anonymous struct:
use *;
use TupleLike;
let alice = stru! ;
print_person;
let bob = stru! ;
print_person;
let empty = stru! ;
print_person; // Of course it is a sub-struct of itself
As generic type
use ident;
use *;
// `R1` and `R2` are "magic", used to indicate the position of the field in the structs,
// and these magic generic types will be automatically inferred by Rust.
// You should introduce a magic generic type for each field.
let person = stru! ;
let earth = stru! ;
print_name_id;
print_name_id;
Details
The implementation of structz is based on stringz and tuplez.
First, macros sort the input fields in lexicographic order, which ensures that anonymous structs with the same fields but different field orders are of the same type.
Second, convert the field names into a specialized type consisting of a sequence of zero-sized types via stringz. Let's call them "field name types".
Finally, pack the field name type and the data type of each field, combine them into
tuplez's Tuple
.
Since the field names is effectively replaced with a zero-sized type, it cost you nothing:
use *;
assert_eq!;