How to write array of objects in rust

Is there any way to create array of objects like these code in rust?

const person = [
  {
    name: "Jhon",
    age: 26,
  },
  {
    name: "Kyle",
    age: 22,
  },
  {
    name: "Tommy",
    age: 17,
  },
];

A direct translation would look something like this, but it's quite restrictive in what you can do with it. In particular, you must know all of the people at compile time. @alice's solution below is more flexible, and probably what you'll actually want in practice.

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
struct Person {
    pub name: &'static str,
    pub age: u32
}

const PEOPLE: &'static [Person] = &[
  Person {
    name: "Jhon",
    age: 26,
  },
  Person {
    name: "Kyle",
    age: 22,
  },
  Person {
    name: "Tommy",
    age: 17,
  },
];
1 Like

I would probably translate your code into something like this:

#[derive(Debug)]
struct Person {
    name: String,
    age: i32,
}

impl Person {
    fn new(name: &str, age: i32) -> Self {
        Self {
            name: name.to_string(),
            age,
        }
    }
}

fn main() {
    let people = vec![
        Person::new("John", 26),
        Person::new("Kyle", 22),
        Person::new("Tommy", 17),
    ];
    
    println!("{:#?}", people);
}
2 Likes

Can i use &str instead, for the name?

Of course. But then you'll have to deal with the lifetime associated with the reference somehow.

1 Like

Yes, but you probably shouldn't. The &str type is best avoided for struct fields.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.