Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/jonhteper/named-ctor
proc-macro to generate constructor functions with syntaxt similar to named params
https://github.com/jonhteper/named-ctor
Last synced: about 1 month ago
JSON representation
proc-macro to generate constructor functions with syntaxt similar to named params
- Host: GitHub
- URL: https://github.com/jonhteper/named-ctor
- Owner: jonhteper
- License: mit
- Created: 2023-09-29T19:55:56.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2023-09-30T04:49:08.000Z (over 1 year ago)
- Last Synced: 2024-08-14T09:58:57.200Z (6 months ago)
- Language: Rust
- Size: 5.86 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# named-ctor
Procedural macro to generate an alternative of named parameters with native Rust.
## Named parameters alternative
Rust don't has support for named parameters, but is possible to use a simulation with data structures.
This alternative is special easy to implement in Rust tanks to `From` trait.For example:
```rust
pub struct User {
id: u8,
name: String,
email: String,
password: String,
is_active: bool,
is_admin: bool,
}impl User {
// ...
}pub struct UserValues {
id: u8,
name: String,
email: String,
password: String,
is_active: bool,
is_admin: bool,
}impl From for User {
fn from(aux: UserValues) -> Self {
Self {
id: aux.id,
name: aux.name,
email: aux.email,
password: aux.password,
is_active: aux.is_active,
is_admin: aux.is_admin,
}
}
}pub fn main() {
let user: User = User::from(UserValues {
id: 0,
email: "[email protected]".to_string(),
name: "John Doe".to_string(),
is_active: true,
password: "1234".to_string(),
is_admin: false,
});
}
```Whats the problem? First, too boilerplate. Second, its not easy to maintain, if `User` is modified, is absolutely necessary modify `UserValues`.
## Using `NamedCtor` macro
The behavior is the same as last example, but now the macro is the responsable to create both aux struct (`_User`) and `From` implementation.
```rust
use named_ctor::NamedCtor;#[derive(NamedCtor)]
pub struct User {
id: u8,
name: String,
email: String,
password: String,
is_active: bool,
is_admin: bool,
}impl User {
// ...
}pub fn main() {
let user: User = User::from(_User {
id: 0,
email: "[email protected]".to_string(),
name: "John Doe".to_string(),
is_active: true,
password: "1234".to_string(),
is_admin: false,
});
}
```
### Macro attributesIs possible to use a custom name for the axiliar struct, and change the
constructor function:```rust
use named_ctor::NamedCtor;
use core::fmt::Display;
#[derive(NamedCtor)]
#[named_ctor(name = "TaskInitValues", constructor = "new")]
pub struct Task<'a, T>
where
T: Display
{
id: T,
name: &'a str,
}
let user: Task<&str> = Task::new(TaskInitValues {
id: "example.id",
name: "Example",
});
```**WARNING**: Generics support only via where clause