[][src]Crate optarg2chain

Converts optional arguments to chaining style.

Rust doesn't have optional or named arguments. This crate provides macros to convert optional arguments given by attributes to method chaining style instead.

Function with optional arguments

Specify optarg_fn for a function with 2 arguments, the name of builder struct and terminal method. Use #[optarg(expr)] to give default value for an argument. #[optarg_default] gives default value by Default::default().

use optarg2chain::optarg_fn;

// specify optarg_fn attribute with builder struct name and terminal method name
#[optarg_fn(JoinStringBuilder, exec)]
fn join_strings(
    mut a: String,                         // Required argument, no default value
    #[optarg_default] b: String,           // String::default() is the default value to b
    #[optarg("ccc".to_owned())] c: String, // "ccc".to_owned() is the default value to c
) -> String {

You can use the generated function as below:

assert_eq!(join_strings("aaa".to_owned()).exec(), "aaaccc"); // Use default values
        .b("yyy".to_owned()) // Pass a value to `b` explicitly
        .c("zzz".to_owned()) // Pass a value to `c` explicitly

Method with optional arguments

Use #[optarg_impl] and #[optarg_method(BuilderStructName, terminal_method_name)] for methods in impl

use optarg2chain::optarg_impl;

struct MyVec<T> {
    data: Vec<T>,

impl<T: Default + Copy> MyVec<T> {
    #[optarg_method(MyVecGetOr, get)]
    fn get_or<'a>(&'a self, i: usize, #[optarg_default] other: T) -> T {

You can use this as below:

let myvec = MyVec { data: vec![2, 4, 6] };
assert_eq!(myvec.get_or(1).get(), 4);
assert_eq!(myvec.get_or(10).get(), 0);
assert_eq!(myvec.get_or(10).other(42).get(), 42);

Attribute Macros


Generates a builder struct and methods for the specified function.


This attribute is used with optarg_method attribute. Specify #[optarg_method(BuilderStructName, terminal_method_name)] to target methods for code generation.