macro_rules! alias {
(
$(
$(#[$attr:meta])*
$vis:vis $name:ident = $expr:expr
);*
$(;)?
) => { ... };
}Expand description
Declares const and type aliases for type-level strings (TStr).
§String Arguments
You can alias a type-level string in these ways:
tstr::alias!{
// Aliases the "bar" type-level string as both a const and a type, named Bar.
// (both the const and type are private to this module)
Bar = bar;
// Aliases the "0" type-level string.
// (both the const and type are private to this crate)
pub(crate) N0 = 0;
// Aliases the "foo" type-level string,
// (both the const and type are public)
pub Tup = "foo";
}Attributes on each alias (including documentation) are copied to the generated constant and type.
§Examples
§Indexing
use std::ops::Index;
let this = Foo { bar: 3, baz: 'X', qux: "8" };
assert_eq!(get_bar_baz(&this), (3, 'X'));
let other = Bar { bar: 13, baz: false, qux: Some('C') };
assert_eq!(get_bar_baz(&other), (13, false));
tstr::alias!{
// Declares both an NBar type alias and an NBar constant of the `TStr` for "bar".
pub NBar = bar;
// Declares both an NBaz type alias and an NBaz constant of the `TStr` for "baz".
pub NBaz = "baz";
// Declares both an NQux type alias and an NQux constant of the `TStr` for "qux".
pub NQux = "qux";
}
type IndexOut<T, N> = <T as Index<N>>::Output;
fn get_bar_baz<T>(this: &T) -> (IndexOut<T, NBar>, IndexOut<T, NBaz>)
where
T: Index<NBar, Output: Copy> + Index<NBaz, Output: Copy>,
{
(this[NBar], this[NBaz])
}
#[derive(Debug)]
pub struct Foo {
bar: u32,
baz: char,
qux: &'static str,
}
impl_field_index!{ Foo,bar[NBar]: u32 }
impl_field_index!{ Foo,baz[NBaz]: char }
impl_field_index!{ Foo,qux[NQux]: &'static str }
#[derive(Debug)]
pub struct Bar {
bar: u32,
baz: bool,
qux: Option<char>,
}
impl_field_index!{ Bar,bar[NBar]: u32 }
impl_field_index!{ Bar,baz[NBaz]: bool }
impl_field_index!{ Bar,qux[NQux]: Option<char> }
macro_rules! impl_field_index {
($Self:ty, $field_name:ident [$field_tstr:ident]: $field_type:ty) => {
impl std::ops::Index<$field_tstr> for $Self {
type Output = $field_type;
fn index(&self, _: $field_tstr) -> &$field_type {
&self.$field_name
}
}
impl std::ops::IndexMut<$field_tstr> for $Self {
fn index_mut(&mut self, _: $field_tstr) -> &mut $field_type {
&mut self.$field_name
}
}
}
} use impl_field_index;