Reputation: 43
I missed something with the initialization of a vector of vectors. In a first approach, I tried this code:
let mut landFirst: Vec<Vec<char>> = Vec::with_capacity(width);
for v in landFirst {
v.push(Vec::with_capacity(height));
}
But it failed:
v.push(Vec::with_capacity(height));
^^^^^^^^^^^^^^^^^^^^^^^^^ expected char, found struct `std::vec::Vec`
Why? v
is composed of Vec<char>
, not of char
.
It works with this code:
let mut landFirst: Vec<Vec<char>> = Vec::with_capacity(width);
for cpt in 0..width {
landFirst.insert(cpt, Vec::with_capacity(height));
}
Can you enlighten me please?
Upvotes: 2
Views: 3731
Reputation: 88636
Why?
v
is composed ofVec<char>
, not ofchar
.
Let's check the type of v
:
for v in land_first {
let () = v;
}
This results in:
error[E0308]: mismatched types
--> src/main.rs:7:13
|
7 | let () = v;
| ^^ expected struct `std::vec::Vec`, found ()
|
= note: expected type `std::vec::Vec<char>`
found type `()`
So the v
has the type Vec<char>
. Why? Well with for v in land_first
you iterate through all elements of land_first
. What are the elements of land_first
? Correct: Vec<char>
.
Another thing you confused: Vec::with_capacity()
only reserves memory, but doesn't actually insert elements. Vec::with_capacity(10).len()
is 0! You need to use push()
or insert()
to actually insert elements.
This also hints at the core problem of your approach: what do you think are the characters in your vectors? You never specified which character to insert. There is no clear default that's always useful, right?
So how would you ideally initialize your vector of vectors? There is the useful vec![]
macro:
const INIT_CHAR: char = '❤';
let land_first = vec![vec![INIT_CHAR; height]; width];
Also note:
landFirst
to land_first
. In Rust, variable names use snake_case
.Upvotes: 6
Reputation: 19416
Firstly, your first code sample is not going to do what you expect, landFirst
is still empty, even if you initialize it with a capacity, it has no items, so the for loop will never be entered.
As you are iterating over the elements of landFirst
, v
is a Vec<char>
, so you can only push a char
to it, your second code sample differs in that you are pushing to landFirst
, not pushing to an element contained within landFirst
.
Your second code sample will properly initialize landFirst
, however it can be rewritten as the following:
let mut landFirst = vec![Vec::with_capacity(height); width];
Upvotes: 4