8.13 Function Overloading
8.13.1 Function Name Overloading
In some languages like C++, you can have multiple functions with the same name but different parameter types (function overloading). In Rust, function overloading based on parameter types is not supported.
- Each function must have a unique name within its scope.
- If you need similar functionality for different types, you can use generics or traits.
Example of Using Traits:
trait Draw { fn draw(&self); } struct Circle; struct Square; impl Draw for Circle { fn draw(&self) { println!("Drawing a circle"); } } impl Draw for Square { fn draw(&self) { println!("Drawing a square"); } } fn main() { let c = Circle; let s = Square; c.draw(); s.draw(); }
- By implementing traits, you can achieve similar behavior without function overloading.
8.13.2 Method Overloading with Traits
Methods can appear to be overloaded when they're defined in different implementations for different types.