How do I use parameter overloading or optional parameters in rust?

后端 未结 1 1134
无人及你
无人及你 2021-01-11 18:47

I am trying to write a print function for a binary tree and here is what I have so far:

impl TreeNode {
    fn print(&self) {
        self.print(0);
             


        
相关标签:
1条回答
  • 2021-01-11 19:19

    Rust does not have overloading, 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 overload with traits. This approach is likely inappropriate for your use case, but you can see how it is done in the standard library, where Path::new() constructor can be called with something resembling a vector of bytes:

    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 via BytesContainer trait, and new() method is defined like this:

    fn new<T: BytesContainer>(bytes: T) -> Path { ... }
    

    Then this trait is implemented for all the types you want:

    impl<'a> BytesContainer for &'a str { ... }
    impl<'a> BytesContainer for &'a [u8] { ... }
    impl BytesContainer for Path { ... }
    // and more
    

    This resembles overloading precisely because new() does exactly the same thing regardless of what kind of input it is provided; it is just a convenience thing which makes Path constructor more flexible. In the end new() just converts its argument to a byte slice. However, this does not allow you to have completely different functions with the same name.

    0 讨论(0)
提交回复
热议问题