structz
Anonymous struct implementation in rust.
Overview
Install
Basically, structz just defines macros, and uses types from tuplez and stringz. Therefore, add them all:
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;
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 deduced 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!;