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 {
            lines.push(line.to_string())
        }

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/lib.rs:6:41
  |
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> = liness.map(String::from).collect();
2 Likes

Thanks, a good lessons for me. :face_holding_back_tears: