On 08/02/2012 12:51 PM, Emmanuel Surleau wrote:
Hi,

I'm new to rust, and I'm struggling to find an elegant way to work with default
parameters.

Generally we've been experimenting with method chaining to achieve things like default and named parameters in Rust. See the task builder API for an example:

https://github.com/mozilla/rust/blob/incoming/src/libcore/task.rs#L197

So I can see your use case being something like:

    let flag = Flag("verbose", "Maximum verbosity").short_name("v");

To implement this you'd write:

    struct Flag {
        name: &str;
        desc: &str;
        short_name: option<&str>;
        max_count: uint;
        banner: option<&str>;
    }

    // Constructor
    fn Flag(name: &str, desc: &str) -> Flag {
        Flag {
            name: name,
            desc: desc,
            short_name: none,
            max_count: 1,
            banner: none
        }
    }

    impl Flag {
        fn short_name(self, short_name: &str) -> Flag {
            Flag { short_name: some(short_name) with self }
        }
        fn max_count(self, max_count: uint) -> Flag {
            Flag { max_count: max_count with self }
        }
        fn banner(self, banner: &str) -> Flag {
            Flag { banner: some(banner) with self }
        }
    }

(Note that this depends on the functional record update "with" syntax working for structs, which it doesn't yet.)

If this style catches on it'd probably be nice to have a macro to generate the mutators (fn short_name, fn max_count, fn banner). Then instead of the "impl { ... }" above you'd write something like:

    make_setter!(Flag.short_name: option<&str>, WrapOption);
    make_setter!(Flag.max_count: uint);
    make_setter!(Flag.banner: option<&str>, WrapOption);

(Assuming that WrapOption is a special flag to the macro to indicate that the value should automatically be wrapped in "some").

How does this sound?

Patrick

_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to