我正在尝试为二叉树编写一个打印函数,这是我目前所拥有的:
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 => ()
};
}
}
我收到错误:值 print
的重复定义。所以我想知道是否有办法创建具有相同名称但参数不同的函数。或者,可选参数可以解决这个问题,但我认为目前这不可能(至少我无法通过 Google 搜索找到它)。
那么,最好的方法是什么?重命名第二个打印函数可行,但看起来很难看,如果我想(对于本例)从树的中间开始打印,则需要记住多个函数名称。
最佳答案
Rust 没有重载,因此不可能有两个具有相同名称和不同参数集的函数或方法。
但是,有时可以用特征来模拟重载。这种方法可能不适合您的用例,但您可以看到它是如何完成的 in the standard library ,其中 Path::new()
构造函数可以用类似于字节向量的东西调用:
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
这是通过 BytesContainer
特性完成的,new()
方法定义如下:
fn new<T: BytesContainer>(bytes: T) -> Path { ... }
然后为所有你想要的类型实现这个特征:
impl<'a> BytesContainer for &'a str { ... }
impl<'a> BytesContainer for &'a [u8] { ... }
impl BytesContainer for Path { ... }
// and more
这恰恰类似于重载,因为无论提供何种输入,new()
都会做完全相同的事情;这只是使 Path
构造函数更加灵活的便利。最后 new()
只是将其参数转换为字节切片。但是,这不允许您拥有同名的完全不同的函数。
关于optional-parameters - 如何在 Rust 中使用参数重载或可选参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24936872/