How store in string variable?

Hello friends, how iterate in vector of string and store a element in variable type String ??

let mut genre_vector: Vec<String> = Vec["pear", "banana"];
for (genre_idx, gen) in genre_vector.iter().enumerate() { 
        let genre_string = gen; // :( 

Thanks for attention

Do you want to take ownership of the strings or clone them?

fn take_ownership() {
    let genre_vector: Vec<String> = vec!["pear".into(), "banana".into()];
    for (genre_idx, gen) in genre_vector.into_iter().enumerate() {
        let genre_string: String = gen;

fn clone() {
    let genre_vector: Vec<String> = vec!["pear".into(), "banana".into()];
    for (genre_idx, gen) in genre_vector.iter().enumerate() {
        let genre_string: String = gen.clone();

1 Like

The question is unclear and has several issues:

  • In Rust, you can declare a vector using the vec![] macro or standard methods (Vec::new and the alike) and not the syntax you used in line 1.
  • Your vector contains string literals (&str), while the type you named is one of a vector of owned strings (String). These are different types, causing a type mismatch.
  • When enumerating the vector and destructuring the tuple, the vector element is saved in the second destructured binding (in this case gen). It remains unclear what you want to do with this value.
  • You might be confusing iteration-by-borrowing with iteration-by-move, as you use the iter() method (which takes a reference) instead of into_iter() (which moves the vector). Using the latter, you could iterate over Strings if you have a Vec<String>.

In any case, you seem to be confusing some basic concepts of the Rust programming language. You might want to take a look at the Rust book and read chapter 8 and chapter 4 regarding vectors and ownership, respectively.


Thanks a lot.

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.