Rust:Using the constructor pattern

内容纲要

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(),
    //     }
    // }
}
点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注