Get-field-by-type
Create a getter for a field based on its type. For example
use GetFieldByType;
let x = A;
assert_eq!;
Why not impl &Self for Into<&T>
Using Into
on references for getting a field is a bit of hack. This is designed for getting the value for a field with a common type. Using a custom trait also means flexibility in the future
Additional options and features
When a struct of variant doesn't have a type, there are two behaviors
Either a compile time error (default)
Or a specified statement to evaluate. This could be a panic
use GetFieldByType;
assert_eq!;
let result = catch_unwind;
assert!;
or returning a constant value
use GetFieldByType;
assert_eq!;
assert_eq!;
Recursive on unit variants
In the AOrB
enum case, the derive macro can't find a i32
on variant AOrB::A
. However, as it is a unit variant, the implementation delegates it to the unit type.
use GetFieldByType;
;
;
let b = B;
assert_eq!;
let a_or_b = B;
assert_eq!;
Alternatives
For more manual field access, check out getset. If looking for getting multiple fields, check out getters-by-type