How to overload methods in Rust.
--
Overloading methods is a commonly used feature in many programming languages. Before turning to further details, let me mention early, in Rust there exists no exact ‘overloading’ of functions. But nevertheless, Rust makes available some techniques that are of upmost importance to avoid code replication and at the same time ensure security as well as its glorified performance.
Note, this story assumes the reader to have some basic knowledge of Rust. If necessary you might find this a helpful introduction.
The problem:
Let us consider the following simple scenario. We want to create a small libraries Utils
that operates on vectors (or matrices) and allows to compute the sine of a vector be component-wise application. That is, we want to write code of the form
let w = Utils::sin(&v);
Here v
could be something like vec![1.0, 2.0]
and w
would be expected to become vec![(1.0).sin(), (2.0).sin()]
.
First approach:
This worked! But wait, this is written to only support vectors of f32
‘s. We also want to support f64
‘s or even vectors of vectors (matrices) like Vec<Vec<f32>>
. By just adding a corresponding version to the impl
of Utils
results in the error
duplicate definitions with name `sin`:
duplicate definitionrustcE0201
Let us next see what kind of mechanism Rust provides for our scenario. You are also invited to contemplate how you would solve this in your favorite (statically typed) language.
Solution:
To solve our problem we will utilize Rust’s Trait
system. The above situation is a very good example to remember for what reason traits do exist in Rust’s ecosystem.