macro_rules! gen_mut {
($m:ty => $code:expr) => { ... };
}
Expand description
This macro simplifies the implementation of generically mutable APIs, where the mutable and the shared code paths are (mostly) identical. It has the following syntax:
gen_mut!{ $M => {
/* code */
}}
where $M
is the name of the generic parameter you want to unwrap.
The code inside has access to three macros, which allow it to emit different code depending on the value of M
:
-
from_gen!($genref)
/from_gen!()
Calls
GenRef::gen_into_shared
andGenRef::gen_into_mut
on the$genref
passed as an argument. The type of return value is different in the shared vs the mutable case, so it is not possible to move the return value outside of the macro call (attempting to do so would run into a type checker error on trying to assign&mut T
to&T
or vice versa). The return value can be converted back into aGenRef
using theinto_gen!
macro. If no arguments are passed, it returns a closureFn(GenRef<'_, M, T>) -> &T
/Fn(GenRef<'_, M, T>) -> &mut T
. -
into_mut!($reference)
/into_mut!(&gen $place)
/into_mut!()
Calls
GenRef::gen_from_shared
andGenRef::gen_from_mut
on the reference passed as an argument, and returns the resultingGenRef
. The type of the input is different in the shared vs the mutable case, so it is not possible to call this with a reference that was not created viafrom_gen!
orswitch_mut_shared!
. To allow accessing fields, you can use theinto_mut!(&gen $place)
syntax, which references the$place
expression with the appropriate kind of reference. If no arguments are passed, it returns a closureFn(&T) -> GenRef<'_, M, T>
/Fn(&mut T) -> GenRef<'_, M, T>
. -
switch_shared_mut!($shared_expr, $mutable_expr)
/switch_shared_mut!({ $shared_tts } { $mutable_tts })
Expands to
shared_expr
in the shared case andmutable_expr
in the mutable case. Theswitch_shared_mut!({ $shared_tts } { $mutable_tts })
syntax allows you to expand to arbitrary token trees, not just expressions. This requires you to wrap them in brackets, which will not appear in the expansion. Also note that in this syntax there is no comma separating the two cases.