Rust:Using the constructor pattern

2020年11月23日 1877点热度 0人点赞 0条评论
内容纲要

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

痴者工良

高级程序员劝退师

文章评论