Collect in practice and vector for novice

Hi, this piece work fine:

let reader = fs::read_to_string("info.txt")
                                    .expect("Except: .txt not exist");
        let liness = reader.lines();
        let mut lines: Vec<String> = Vec::new();
        for line in liness {

let mut lines: Vec = liness.collect(); // :frowning:
error: .collect();
| ^^^^^^^ value of type Vec<String> cannot be built from std::iter::Iterator<Item=&str>

how i do using collect?

The error msg already shows itself. You can't iterate &str to gain a vec of String. The elements are of distinct types.

error[E0277]: a value of type `Vec<String>` cannot be built from an iterator over elements of type `&str`
 --> src/
6 |     let mut lines: Vec<String> = liness.collect();
  |                                         ^^^^^^^ value of type `Vec<String>` cannot be built from `std::iter::Iterator<Item=&str>`
  = help: the trait `FromIterator<&str>` is not implemented for `Vec<String>`
  = help: the trait `FromIterator<T>` is implemented for `Vec<T>`

So the solutions can be

    // a vec of &str
    let mut lines: Vec<&str> = liness.collect();
    // or a vec of owned String
    let mut lines: Vec<String> =;

Thanks, a good lessons for me. :face_holding_back_tears:

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.