Search code examples
objectrustinitialization

Object declaration and initialization in Rust


pub struct Person
{
    name: String,
    age: u32,
}

impl Person {
    pub fn new(name: String, age: u32) -> Person {
        Person { name, age }
    }
    pub fn show(self)
    {
        println!("Name: {}, Age: {}", self.name, self.age);
    }
}

fn main()
{
    let person = Person { name: "Alice".to_string(), age: 33 }; // (1)<<<<<<<<<<<<<
    let person2 = Person::new("Bob".to_string(), 99 );// (2)<<<<<<<<<<<<<
}

What is the difference between (1) and (2) in the above source code?


Solution

    1. Direct struct instantiation syntax. Because the fields name and age are not marked pub, this can only be used within the module it's defined.

    2. Function call construction. Since the function is pub, it can be used from any module that can access Person.

    Other than the visibility difference, both will act identically.