Can we make vector of structs ? if yes than how to make and use it


#1

my question is that, can I make a vector of structs like

struct data {
	g: i8
	h: i8
}
let mut j : Vec<data> = Vec::new();

this might look like idiotic and I think it not even possible as I see no way of accessing or filling this vector


#2
let j = vec![data{g: 3, h: 4}, data{g: 99, h: 42}];

Why should this not work? You are creating a vec and specify each element you want to insert.


#3

so i can directy use vector.push();?


#4

Sure. Why don’t you try it? :wink:

Here’s the solution, try it first on your own!

let mut v = vec![];
v.push(data{g: 3, h: 4});
v.push(data{g: 99, h: 42});

#5
struct Data {
    	g: i32,
    	h: i32,
    }

fn main() {
	let mut x :Vec<Data> = Vec::new();
	let (mut p, mut m) : (i32,i32) = (1,100) ;
	let mut k = 0 ;
	let mut some = Data {g:0,h:0};
	loop {
		some.g = p; some.h = m ;
		x.push(some);
		m+=1;
		p+=1;
		k+=1;
		if k==100 {break;}
	}
}

and error goes like :
C:\Users\Dell\Desktop\rust\learn\structs>cargo build
Compiling structs v0.1.0 (file:///C:/Users/Dell/Desktop/rust/learn/structs)
error[E0382]: use of moved value: some
–> src\main.rs:27:10
|
27 | x.push(some);
| ^^^^ value moved here in previous iteration of loop
|
= note: move occurs because some has type Data , which does not implement the Copy trait

error: aborting due to previous error

For more information about this error, try rustc --explain E0382 .
error: Could not compile structs .

To learn more, run the command again with --verbose.


#6

In short, swap these lines

let mut some = Data {g:0,h:0};
loop {

In long, this is not very “rusty” (a rust idiomatic way of writing code). Here are a few hints:

  1. you don’t need to specify the type of variables, just let the compiler deduce it
  2. Don’t use mut, when not absoluty necessary
  3. instead of loop ... break just use a conditional for loop. It’s easier to read and better to maintain
  4. Don’t increment loop counter by yourself, it’s very error prone (not only in rust, but in every language).

Here’s my “solution” of your code. It’s much shorter and IMHO better to read.

#[derive(Debug)]
struct Data {
    g: i32,
    h: i32,
}

fn main() {
    let mut x = Vec::new();
    for p in 1..=101 {
        let m = p+99;
        let some = Data {g:p,h:m};
        x.push(some);
    }
    println!("{:?}", x);
}

#8

one more trouble

here is the code

 struct Data {
    	g: i32,
    	h: i32,
    }

fn main() {
	let mut x :Data = Vec::new();
	let mut q = 0 ;
	for p in 1..=100 {
		p = q+99;
  		let some = Data {g:p,h:q};
  		x.push(some);
	}
	for s in 1..101 {
		let mut sam = x[s];
		println!("these datas {} , {} ",sam.g,sam.q);
	}
}

errors are:

C:\Users\Dell\Desktop\rust\learn\structs>cargo build
   Compiling structs v0.1.0 (file:///C:/Users/Dell/Desktop/rust/learn/structs)
error[E0308]: mismatched types
  --> src\main.rs:19:20
   |
19 |     let mut x :Data = Vec::new();
   |                       ^^^^^^^^^^ expected struct `Data`, found struct `std::vec::Vec`
   |
   = note: expected type `Data`
              found type `std::vec::Vec<_>`

error[E0599]: no method named `push` found for type `Data` in the current scope
  --> src\main.rs:24:7
   |
1  |  struct Data {
   |  ----------- method `push` not found for this
...
24 |           x.push(some);
   |             ^^^^

error[E0608]: cannot index into a value of type `Data`
  --> src\main.rs:28:17
   |
28 |         let mut sam = x[s];
   |                       ^^^^

error: aborting due to 3 previous errors

Some errors occurred: E0308, E0599, E0608.
For more information about an error, try `rustc --explain E0308`.
error: Could not compile `structs`.

To learn more, run the command again with --verbose.

C:\Users\Dell\Desktop\rust\learn\structs>

#9

Just listen to the compiler. I won’t tell you the answer right away this time. All errors are very simple and clear (and mostly statet in my four points above)

  1. you don’t need to specify the type of variables, just let the compiler deduce it
  2. Don’t use mut , when not absoluty necessary
  3. instead of loop ... break just use a conditional for loop. It’s easier to read and better to maintain
  4. Don’t increment loop counter by yourself, it’s very error prone (not only in rust, but in every language).

"expected struct Data, found struct std::vec::Vec" -> point 1

(after fixing that you will occur more errors)

"no field q on type Data" -> this should be easily done
"cannot assign twice to immutable variable p" -> spelling mistake? Watch carefully and avoid q and g because they are very simlar when you read something
“cannot move out of indexed content” -> the compiler will give you the hint, what to do

Also you will receive some warnings (mostly regarding to not used (I think a mistake) and point 2).

I hope you will figure that one out.