An implementation of function overloading, named arguments and optional arguments in Rust

71 points TiDuNguyen

Comming from higher level languages, we often miss the flexibility when creating and using functions in Rust. Rust functions by default does not have features like:

  • function overloading (typically found in C++/Java/JS/C#)
  • optional arguments (basic thing in Python)
  • named arguments (basic thing in Python)

Many people have said that Rust can already provide those features through traits , generics , and structs. However, I have yet to find any concrete example and thorough walkthrough/tutorial regarding this, especially on the analysis of the pros and cons of the implementation.

As a result, I tried to implement those features myself. Turned out, they are not that complicated, requiring exactly traits , generics , and structs, no macro, no nightly feature. Here is my implementation:

https://github.com/tidunguyen/flexible-fn-rs

I would love to share my implementations:

  • as a reference so that others can build on top of that to provide more complex, yet flexible API
  • to receive feedbacks on things that can be improved in my implementations as I'm not that good in Rust yet, especially for things that I'm not totally confident that it will work without side effects like the removal of Sized bound on generic type param.
  • to serve as a proof that Rust can also have flexible functions