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


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

You must enable javascript to see captcha here!