[rust-dev] Polymorphism & default parameters in rust

Tim Chevalier catamorphism at gmail.com
Thu Aug 2 13:00:43 PDT 2012

On Thu, Aug 2, 2012 at 12:51 PM, Emmanuel Surleau
<emmanuel.surleau at gmail.com> wrote:
> Hi,
> I'm new to rust, and I'm struggling to find an elegant way to work with default
> parameters.
> I'm trying to implement in rust the equivalent of the following Python line:
> def flag(self, name, desc, short_name=None, max_count=1, banner=None):
>     ...
> The idea is to offer a "simple" API (with only name and desc mandatory, while
> making available number of advanced options if needed).
> My first move was to try polymorphism:
> fn a(x: ~str) -> ~str {
>     #fmt("First function with %s", x)
> }
> fn a(x: ~str, y: ~str) -> ~str {
>     #fmt("Second function with %s and %s", x, y)
> }
> fn main() {
>     #info("Result: ");
> }
> Oddly enough, this compiles, but the first function is shadowed by the second,
> so attempting a(~"something") does not compile. I assume this is not an intended
> behaviour.

Hi, Emmanuel --

I believe that the behavior you're observing is a bug; you shouldn't
be able to declare two top-level function items with the same name,
even if the types differ. So please file an issue with this code:



> Further research hasn't turned any solution. Is there some idiomatic way in rust
> of having defaults for parameters?

A simple way to do it is with option types:

fn a(x: ~str, y: option<~str>) -> ~str {
 /* do whatever */

fn a_1(x: ~str) -> ~str {
  a(x, none)

You may be able to use traits and impls to overload the name a, but if
you don't mind giving the different functions different names, this
way doesn't require any fancy ideas.


Tim Chevalier * http://catamorphism.org/ * Often in error, never in doubt
"Debate is useless when one participant denies the full dignity of the
other." -- Eric Berndt

More information about the Rust-dev mailing list