what should be the signature of a function that returns a vector of vector of strings ?
something like :
[["one", "two", "three", "four"], ["apple", "ball", "car", "doll"], [" cat", "dog", "mouse", "lion"]]
what should be the signature of a function that returns a vector of vector of strings ?
something like :
[["one", "two", "three", "four"], ["apple", "ball", "car", "doll"], [" cat", "dog", "mouse", "lion"]]
It could be something like this:
fn abc() -> Vec<Vec<String>> {
vec![vec![]]
}
Thanks for the reply !
I tried the same...
But i got the following error :
expected struct std::string::String
, found &std::string::String
Try dereferencing the string and then move it into the vector (unless it's owned by another function).
Sharing your code would be helpful
let s: &String = &String::from("abc");
vec.push(*s);
I am trying to read data from a csv file and want to store the data in a vector of vector
This is what I wrote :
fn get_data() -> Vec<Vec<String>> {
let mut rows = Vec::new();
let mut csv_read = csv::Reader::from_reader(io::stdin());
for line in csv_read.deserialize() {
let mut each_row = Vec::new();
let record:Record = line?;
for (header, value) in record.iter() {
let v: &String = &String::from(value);
each_row.push(*v)
}
rows.push(each_row)
}
rows
}
Then I got the following error :
let record:Record = line?;
^^^^^ cannot use the `?` operator in a function that returns `std::vec::Vec<std::vec::Vec<std::string::String>>`
Can you help me in figuring this out !
The ?
operator will check if the result of line
is Ok
, it it is - it will be unwrapped into record. Otherwise the Err
part of the result will be returned. The problem: The function doesn't return a Result
that can accept line's Err
type.
Possible solutions:
Result<Vec<Vec<String>>, Error>
.Thank you so much !!!
Using unwrap() worked !
If I want to return csv_read directly from the above that I had written earlier, what should be the return type of the function ?
How to resolve the following error :
move occurs because value has type std::string::String
, which does not implement the Copy
trait
Please provide sufficient code.
You probably have something like this in the code:
let x = vec[i];
The problem is that the owned String
can exist in one place only. If it's in x
variable, then it can't exist in vec
any more. Rust will not do magic bookkeeping for you to know where a "hole" in the vec is after the string has been moved out of it into a variable.
You can do:
let xcopy = vec[i].clone();
or
let xref = &vec[i];
to borrow the string instead of removing it from the vector.
Or if you want to remove strings from the vector, use Option<String>
and .take()
or vec.remove(i)
/vec.swap_remove(i)
.
Thanks for your suggestion !
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.