Skip to content

Easily declare complex struct

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT
Notifications You must be signed in to change notification settings

storycraft/impl-opaque

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

44 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

impl-opaque

Documentation

Declare struct fields and initializers in implementation area.

This macro tries to solve separation of field declarations, initializations and usages. The opaque attribute generates struct declaration, struct constructor (new method) by collecting field declarations and initializers inside impl block.

This crate is no_std on runtime and requires alloc to build macro.

Features

  1. Declare fields inside method
#[opaque]
impl Struct {
    fn run(&mut self) {
        #[field]
        let ref mut count: i32 = 0;
        *count += 1;

        println!("{}", count);
    }
}
  1. Declare fields inside impl block
#[opaque]
impl Struct {
    field!(count: i32 = 0);

    fn run(&mut self) {
        self.count += 1;
        println!("{}", self.count);
    }
}
  1. Convert constructor arguments into fields
#[opaque(pub(self) count: i32)]
impl Struct {
    fn run(&mut self) {
        self.count += 1;
        println!("{}", self.count);
    }
}
  1. Declare struct and implement trait at once
#[opaque]
impl Iterator for Struct {
    type Item = i32;

    fn next(&mut self) -> Option<i32> {
        #[field]
        let ref mut count: i32 = 0;
        *count += 1;

        Some(*count)
    }
}
  1. Pattern matching and early return for fields inside a method
#[opaque]
impl Struct {
    pub fn run(&mut self) {
        #[field]
        let ref mut running @ true: bool = true else {
            return
        };

        println!("run");
        *running = false;
    }
}

Attributes below #[opaque] will be moved to struct declaration. Attributes below #[field] and field!() will be moved to field declaration.

Attribute reference

#[opaque($(as $vis $(const)? ,)? $($($vis)? $ident: $ty),*)]

Examples

See examples for simple example

License

This crate is licensed under MIT OR Apache-2.0

About

Easily declare complex struct

Resources

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT

Stars

Watchers

Forks

Packages

No packages published

Languages