Rust has no overload, so it is impossible to have two functions or methods with the same name and with different sets of parameters.
However, it is sometimes possible to emulate an overload using features. This approach is probably not suitable for your use case, but you can see how it is done in the standard library , where you can call the constructor Path::new() with something resembling a byte vector:
Path::new("/a/b/c/d") // argument is &str Path::new(b"/a/b/c/d") // argument is &[u8] Path::new(Path::new("/a/b/c/d")) // argument is another Path
This is done using the BytesContainer attribute, and the new() method is defined as follows:
fn new<T: BytesContainer>(bytes: T) -> Path { ... }
Then this attribute is implemented for all types that you want:
impl<'a> BytesContainer for &'a str { ... } impl<'a> BytesContainer for &'a [u8] { ... } impl BytesContainer for Path { ... }
This is similar to overloading precisely because new() does exactly the same thing no matter what input is entered; it's just a convenient thing that makes the Path constructor more flexible. At the end, new() simply converts its argument to a byte slice. However, this does not allow you to have completely different functions with the same name.
Vladimir Matveev
source share