Array of structure

how to make an array of structure in rust language
like in c
struct car
{
char make[20];
char model[30];
int year;
};

struct car arr_car[10];

You have to initialize your structures and arrays in Rust. So if you want an array with 10 Cars, you have to write 10 Car literals. There is a shortcut with Vec, which can be dynamically sized. E.g. allocate an empty Vec<Car> and push Cars into it at runtime.

is it possible to initialize array size and then input each element using for loop

This kind of thing is often done with macros, so that your code never ends up in a situation where uninitialized data could be used. For example, if your for-loop did some non-trivial work and caused a panic in the middle of iteration, that would leave your array with some uninitialized data. And you could go on to introduce undefined behavior and break all of Rust's safety guarantees. The macro will move the loop to compile-time, introducing all elements into the AST so that initialization is infallible.

There are also some other tricks, which usually involve unsafe or relying on a crate that upholds the safety contract with unsafe. The macro is probably a good place to start.

You can't initialize an array with a for loop. Rust programs don't use fixed-size arrays the same way C does.

In your case it should be:

struct Car
{
make: String,
model: String,
year: i32,
}

let arr_car = Vec::new()

If you're very concerned about avoiding heap allocation in this case, then there are crates like arrayvec that have flexibility of Vec/String, but use fixed-size storage like C's char[n].

1 Like

If you need to "initialize array size" at runtime (i.e. from user input), you need not an array, but the Vec.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.