RJB
RJB

Reputation: 115

How to properly store and access Vector to other functions in Rust

I'm trying to create a simple program in Rust that will add, retrieve, and delete a Person.

main.rs

mod person;
fn main {
  person::add("Mr", "Wang", "Li", "Lou");
}

person.rs

#[derive(Debug)]
pub struct Person {
    prefix: String,
    first_name: String,
    middle_name: String,
    last_name: String,
}

pub fn add(prefix: String, first_name: String, middle_name: String, last_name: String) {
    let new_person: Person = Person {
        prefix,
        first_name,
        middle_name,
        last_name,
    };

    println!("New person added: {:?}", new_person);
}

pub fn list() {
    // will print list of Person
}

Inside the person::add() I wanted to create a collection of persons where I can push the new data new_person which I can also use to retrieve it from the pub fn list().

Upvotes: 1

Views: 494

Answers (1)

Jihyeon Kim
Jihyeon Kim

Reputation: 111

You generally don't want to declare a global variable in Rust. It's quite different from what you asked but this is generally how you write in Rust.

// main.rs
mod person;

use person::Person;

fn main() {
    let mut people = Vec::new();

    people.push(Person::new("Mr", "Wang", "Li", "Lou"));
    people.push(Person::new("Mr", "Johann", "Sebastian", "Bach"));
    people.push(Person::new("Mr", "Winston", "S.", "Churchill"));
    
    println!("{:?}", people);
}
// person.rs
#[derive(Debug)]
pub struct Person {
    prefix: String,
    first_name: String,
    middle_name: String,
    last_name: String,
}

impl Person {
    pub fn new(prefix: &str, first_name: &str, middle_name: &str, last_name: &str) -> Self {
        Person {
            prefix: prefix.to_string(),
            first_name: first_name.to_string(),
            middle_name: middle_name.to_string(),
            last_name: last_name.to_string(),
        }
    }
}

Click to see how these codes actually works in the Rust Playground

Probabily these links will help you further

Upvotes: 2

Related Questions