Rust also does not have a builtin notion of overloading methods. There are some ugly workarounds but the idiomatic way of solving this is to provide methods with separate signatures.
Option1
- Determine all Methods with identical name
- Parse their arguments and try to determine how arguments can be combined.
Let’s assume that we have the following methods.
void set_name(int idx, int port, const char* name);
void set_name(int port, const char* name);
void set_name(const char* name);
In Rust, we define 3 methods for the bindings with different names. We link them to generated C++
methods with the same name.
mod ffi {
fn set_name1(idx: i32, port: i32, name: &str);
fn set_name2(port: i32, name: &str);
fn set_name3(name: &str);
}
We can then write one method with optional arguments which calls one of these 3 methods depending on which argument is specified.
fn do(port_idx: Option<(i32, Option<i32>)>, name: &str) {
match (port_idx) {
Some((idx, Some(port))) => ffi::set_name1(idx, port, name),
Some((idx, None)) => ffi::set_name2(port, name),
None => ffi::set_name3(name),
}
}
Option2
Another way would be to determine the “meaning” of the parameters and thus define new methods with different names. We would still need to make sure that they do not collide with already present ones. For example:
void set_name(int port, const char* name);
void set_name(const char* name);
could be converted to
mod ffi {
fn set_name_with_port(port: i32, name: &str);
fn set_name(name: &str);
}
This could be very problematic in the case where we have unnamed arguments.
Summary
I think that there are some tradeoffs between discoverability, overall code-size, conciseness and type ergonomics. Especially Option2 is hard to solve since automatically generating function names would require me to have good understanding of their effect which is of course not guaranteed by only parsing argument names or not doable (unnamed arguments).
I personally prefer the readability of Option2 but I am not settled on this yet. I think I would see what the situation is in practise and if I can generate these function names somewhat reasonably even if I have to use some heuristics to determine a suitable name.