If I have two vectors and the elements in the vector are structs, what I want to implement is to add elements in one vector to the other vector, similar to final_order = final_order + ordered;
you can add a mutable reference to the first one and use the .extend
method
Do you mean concatenate?
let mut a = vec!['a', 'b', 'c'];
let mut b = vec!['d', 'e', 'f'];
b.append(&mut a);
assert!( b == vec!['a', 'b', 'c', 'd', 'e', 'f'] );
Append will move all items from one vector to the end of the other.
My code is as follows:
let mut final_order = Vec::new();
let mut ordered = Vec::new();
final_order = final_order.extend(ordered);
But this error occurs:
mismatched types
expected struct 'Vec< Certificate> '
found unit type '()'
You are probably expecting to return a Vector from a function. The semicolon at the end makes the implicit return to be the Unit type.
Btw, please format your code.
Yes, I returned final_order and my return value type is Vec; But I still don't understand this error
My code is as follows:
let mut final_order = Vec::new();
let mut ordered = Vec::new();
final_order = final_order.append(&mut ordered);
But this error occurs:
mismatched types
expected struct 'Vec< Certificate> '
found unit type '()'
I returned final_order, and the return type of the function is Vec< Certificate> I really don't know why there is this error
look at the signature of append
Maybe this helps you to understand:
A function can return a value if explicitly specified:
fn myFunc() -> Vec<usize> {
let myVec = vec![1, 2, 3];
return myVec;
}
But you can also make the return implicit:
fn myFunc() -> Vec<usize> {
let myVec = vec![1, 2, 3];
myVec // <- This function will return myVec, even when there's no "return" word.
}
Note that in the example above for the implicit return I didn't add a semicolon. Adding it turns the return type to be ()
(Also known as the Unit type) instead of Vec<usize>
.
fn myFunc() -> Vec<usize> {
let myVec = vec![1, 2, 3];
myVec; // <- The semicolon here is a mistake, and this will fail to compile.
}
Expanding on my previous answer (I was on my phone), on line 3 here you're trying to assign the return value of append
to final_order
.
append
returns ()
but final_order
is a Vec
.
append
modifies its Vec
, it doesn't return a new one.
Thank you very much. With the help of you and another friend, I solved my problem. Thank you again.
Dear friends, thank you very much, with the help of you and another friend, I solved my problem, thank you again,
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.