How to overload the 'new' method?

拥有回忆 提交于 2019-12-19 04:06:31

问题


I'm just started to learn Rust and I'm wondering if there is way to overload methods. At first I created a struct and used a 'impl' to implement basic 'new' method. Then I thought to add 'new' method with some params, and I tried to use trait for that.

The following code was successfully compiled but once I tried to use 'new' with params, compiler gave me an error about extra params. So how should I overload methods in Rust?

pub struct Words<'a> {
    pub nouns: Vec<&'a str>,
}

trait Test<'a>{
    fn new(nouns: Vec<&'a str>) -> Self;
}

impl<'a> Words<'a> {
    pub fn new() -> Words<'a>{
        let nouns = vec!["test1", "test2", "test3", "test4"];
        Words{ nouns: nouns }
    }

    pub fn print(&self){
        for i in self.nouns.iter(){
            print!("{} ", i);
        }
    }
}

impl<'a> Test<'a> for Words<'a> {
    fn new(nouns: Vec<&'a str>) -> Words<'a>{
        Words{ nouns: nouns }
    }
}

回答1:


Rust indeed has overloading via traits, but you can't change the number of parameters, and their types can only be changed if they were declared as generic on the first place in the trait definition.

In cases like yours, it's common to have a method like new_with_nouns to specialize what you mean:

impl<'a> Words<'a> {
    fn new() -> Words { /* ... */ }
    fn new_with_nouns(nouns: Vec<&'a str>) -> Words<'a> { /* ... */ }
}

For more complex data structures, where the new_with_something pattern would lead to a combinatorial explosion, the builder pattern is common (here I'll assume that Words has a separator field, just to demonstrate):

struct WordsBuilder<'a> {
    separator: Option<&'a str>,
    nouns: Option<Vec<&'a str>>,
}

impl<'a> WordsBuilder<'a> {
    fn new() -> WordsBuilder<'a> {
        WordsBuilder { separator: None, nouns: None }
    }

    fn nouns(mut self, nouns: Vec<&'a str>) -> WordsBuilder<'a> {
        self.nouns = Some(nouns);
        self
    }

    fn separator(mut self, separator: &'a str) -> WordsBuilder<'a> {
        self.separator = Some(separator);
        self
    }

    fn build(self) -> Words<'a> {
        Words {
            separator: self.separator.unwrap_or(","),
            nouns:     self.nouns.unwrap_or_else(|| {
                vec!["test1", "test2", "test3", "test4"]
            })
        }
    }
}

This is similar to how the stdlib's thread::Builder works, for example.



来源:https://stackoverflow.com/questions/28000113/how-to-overload-the-new-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!