Skip to content

Add a simpler version of read_lines #1480

Closed
@samoylovfp

Description

@samoylovfp

Hello! First of all thanks for the amazing resource!

The read_lines example features an optimized way of reading lines from a file with a BufReader.

The code is efficient but is pretty involved and makes a newcomer stumble, forcing them to read about Results, BufReaders, AsRef and generics with a where clause.

My new-to-rust friend ran into this when trying to solve challenges from Advent of Code.

Most challenges from AoC require reading a sequence of lines from an input file and I feel it would be good to also have a less efficient example that exposes less new concepts to a newcomer, because this is the first thing you run into when trying to solve an AoC challenge.

Example

fn read_lines(filename: &str) -> Vec<String> {
    read_to_string(filename) 
        .unwrap()  // panic on possible file-reading errors
        .lines()  // split the string into an iterator of string slices
        .map(String::from)  // make each slice into a string
        .collect()  // gather them together into a vector
}

or

fn read_lines(filename: &str) -> Vec<String> {
    let mut result = Vec::new();

    for line in read_to_string(filename).unwrap().lines() {
        result.push(line.to_string())
    }

    result
}

I am still not happy about having to mention &str to String conversion but I feel like even though these examples are longer they apply less cognitive pressure to someone not familiar with rust

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions