内容目录
Using the constructor pattern
You may have asked yourself how to idiomatically initialize complex structs in Rust, considering it doesn't have constructors. The answer is simple, there is a constructor, it's just a convention rather than a rule. Rust's standard library uses this pattern very often, so we need to understand it if we want to use the std effectively.
在各种复杂的结构体中,我们需要学会使用构造函数合理地初始化结构体。
定义一个结构体:
struct NameLength {
name: String,
length: usize,
}
为其增加 new 函数(构造函数):
impl NameLength {
// The user doesn't need to setup length
// We do it for him!
fn new(name: &str) -> Self {
let result = NameLength {
name: name.to_string(),
length: name.len(),
};
return result;
}
// fn new(name: &str) -> Self {
// NameLength {
// name: name.to_string(),
// length: name.len(),
// }
// }
}
文章评论