内容目录
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.
In various complex structs, we need to learn to reasonably initialize the struct using a constructor.
Define a struct:
struct NameLength {
name: String,
length: usize,
}
Add a new function (constructor) for it:
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(),
// }
// }
}
文章评论