use*_*299 7 overloading optional-parameters rust
我正在尝试为二叉树编写打印函数,这是我到目前为止的内容:
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 => ()
};
}
}
Run Code Online (Sandbox Code Playgroud)
我收到错误:重复定义值print
.所以我想知道是否有办法创建具有相同名称但不同参数的函数.或者可选参数可以解决这个问题,但我认为目前不可能(至少我无法通过谷歌搜索找到它).
那么,最好的方法是什么?重命名第二个打印功能但看起来很丑,如果我想(从本例中)打印从树的中间开始,则需要记住多个函数名.
Vla*_*eev 10
Rust 没有重载,因此不可能有两个具有相同名称和不同参数集的函数或方法。
但是,有时可以使用特征来模拟过载。这种方法可能不适合您的用例,但您可以在标准库中看到它是如何完成的,其中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
Run Code Online (Sandbox Code Playgroud)
这是通过BytesContainer
trait完成的,new()
方法定义如下:
fn new<T: BytesContainer>(bytes: T) -> Path { ... }
Run Code Online (Sandbox Code Playgroud)
然后为您想要的所有类型实现此特征:
impl<'a> BytesContainer for &'a str { ... }
impl<'a> BytesContainer for &'a [u8] { ... }
impl BytesContainer for Path { ... }
// and more
Run Code Online (Sandbox Code Playgroud)
这类似于重载,因为new()
无论提供什么样的输入,它都会做完全相同的事情;它只是一个方便的东西,使Path
构造函数更加灵活。最后new()
只是将其参数转换为字节切片。但是,这不允许您拥有完全不同的同名函数。