如何在生锈中使用参数重载或可选参数?

时间:2014-07-24 14:43:18

标签: optional-parameters rust overloading

我正在尝试为二叉树编写打印函数,这是我到目前为止所做的:

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搜索找到它)。

那么,最好的方法是什么?重命名第二个打印功能但看起来很丑,如果我想(从本例中)打印从树的中间开始,则需要记住多个函数名。

1 个答案:

答案 0 :(得分:4)

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()只是将其参数转换为字节切片。但是,这不允许您使用相同名称的完全不同的功能。

相关问题