How to use parameter overload or additional parameters in rust?

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

impl TreeNode { fn print(&self) { self.print(0); } fn print(&self, level: u8) { for _i in range(0,level) { print!("\t"); } match self.data { Some(x) => println!("{}",x), None => () }; match self.left { Some(ref x) => x.print(level+1), None => () }; match self.right { Some(ref x) => x.print(level+1), None => () }; } } 

I get an error: duplicate definition of print value. So I was wondering if there is a way to create functions with the same name but with different arguments. Alternatively, additional options can solve this problem, but I donโ€™t think it is possible at the moment (at least I could not find it through a Google search).

So what is the best way to do this? Renaming the second print function works, but it looks ugly and requires you to remember more than one function name if I want to (for this example) print from the middle of the tree.

+7
optional-parameters function-overloading rust
source share
1 answer

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 { ... } // and more 

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.

+4
source share

All Articles