Different implementations for struct methods

Sorry if my question is not new, but in few words,
is it possible to give same name to methods using different arguments (like in C++)

struct Foo {
  fn bar(){}
  fn bar(i:i32){}
  // ..
}

Seems short answer is no, but maybe I should learn something around generics or implementations to make flexible API for my library in Rust?

Thanks

Correct.

You can make a trait with a generic type parameter and take that as an argument (then implement it multiple times). But it would be unidiomatic, so I suggest you don't do that. Try to figure out what would be idiomatic in Rust for your use case (vs. C++). (Option<i32> maybe? Or different methods.)

2 Likes

You cannot overload methods defined on a struct, but you can do some kind of overloading by defining the two methods on separate traits and implementing both traits for the struct. Whether that makes sense depends on your actual use case.

2 Likes

That's worse IMO because you won't be able to call the trait methods with method call syntax.

https://doc.rust-lang.org/reference/expressions/method-call-expr.html

1 Like

Not within the same module, no.

1 Like

There are a few common patterns for supporting calling a method with different arguments:

  1. Make method arguments enums (eg. fn bar(i: Option<i32>))
  2. Add methods with different names to the trait. Some of these might be convenience methods that have default implementations which forward to the "main" method that supports all the arguments.
  3. Make method arguments generic. For example the signature of File::open is fn open<P: AsRef<Path>>(path: P) -> Result<File>. This allows the open method to accept a path in various formats (String, str, Path) which are internally all converted to a common format.

A downside of approach (3) is that such methods will no longer be available on dyn Trait objects, for the same reason that virtual methods cannot be templates in C++.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.