Join Medium with my referral link - applied.math.coding
Get access to all of my stories and to thousands more on Medium from other writers. As my strong believe is, Medium is…
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.
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);
v could be something like
vec![1.0, 2.0] and
w would be expected to become
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
Utils results in the error
duplicate definitions with name `sin`:
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.
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.