Macro kas_macros::impl_anon

source ·
impl_anon!() { /* proc-macro */ }
Expand description

Construct a single-instance struct

Rust doesn’t currently support impl Trait { ... } expressions or implicit typing of struct fields. This macro is a hack allowing that.

Example:

use std::fmt;
fn main() {
    let world = "world";
    let says_hello_world = kas::impl_anon! {
        struct(&'static str = world);
        impl fmt::Display for Self {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                write!(f, "hello {}", self.0)
            }
        }
    };
    assert_eq!(format!("{}", says_hello_world), "hello world");
}

That is, this macro creates an anonymous struct type (must be a struct), which may have trait implementations, then creates an instance of that struct.

Struct fields may have a fixed type or may be generic. Syntax is as follows:

  • regular struct: ident: ty = value
  • regular struct: ident: ty (uses Default to construct value)
  • tuple struct: ty = value
  • tuple struct: ty (uses Default to construct value)

The field name, ident, may be _ (anonymous field).

Refer to examples for usage.