Is this factory and how do I make constructor for struct?

Viewed 304
struct Person{
    name: String
}

fn person_factory(name: String)-> Person {
    Person{
        name,
    }
}

fn main() {
    let p1 = person_factory("Viktor Draganov".to_string());

    println!("{}", p1.name);
}

Is this factory in rust? And how can I initialize person from constructor?

1 Answers

person_factory does look like a factory (if not a particularly useful or necessary one). Usually factories exist to abstract some creation logic away from the user. Such as converting a date of birth to an age when creating a person.

Rust does not have any special method that works like a constructor you'd be familiar with from languages like Java, Python, C++, etc; however, there is a common practice that provides essentially the same behavior as described in this site which covers Rust design patterns: Constructors.

Following this article you could make a "constructor" for your Person class like this (it should look VERY similar to the factory method you shared above):

struct Person{
    name: String
}

impl Person {
    pub fn new(name: String) -> Self {
        Person {
            name: name
        }
    }
}

fn main() {
    let p1 = Person::new("Viktor Draganov".to_string());

    println!("{}", p1.name);
}

Related