如何重载“新"方法? [英] How to overload the 'new' method?
问题描述
我才刚刚开始学习Rust,我想知道是否有方法可以重载方法. 首先,我创建了一个结构,并使用了"impl"来实现基本的"new"方法.然后我想添加带有一些参数的'new'方法,然后尝试使用trait.
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.
以下代码已成功编译,但是一旦我尝试对参数使用'new',编译器就会给我一个关于额外参数的错误. 那么我应该如何在Rust中重载方法呢?
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 }
}
}
推荐答案
铁锈确实确实因特质而超载,但您不能更改参数的数量,并且只有在将参数声明为泛型的情况下才能更改它们的类型.性状定义中的第一名.
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.
在像您这样的情况下,通常会使用类似new_with_nouns
的方法来专门说明您的意思:
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> { /* ... */ }
}
对于更复杂的数据结构(其中new_with_something
模式将导致组合爆炸),构建器模式是常见的(在这里,我假设Words
具有一个separator
字段,只是为了演示):
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"]
})
}
}
}
这类似于 stdlib的thread::Builder
例如,有效.
This is similar to how the stdlib's thread::Builder
works, for example.
这篇关于如何重载“新"方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!