Why the stdin::prelude?

hi rustaceans,

I am still a newbie in rust and have a non CS Js and python only background.
I was trying to read a line and then all lines from stdin into an vec[tor] and I stumbled upon the docs about stdin lock and lines and saw you need to import the io::stdin like this:

use std::io::stdin;
use std::io::prelude::*;

to use it like this:

for line in stdin().lock().lines() { ... }

I am now confused. why the need for use std::io::prelude::*;. without it the lines() do not seam to exist on the return from lock()

cargo says:

error[E0599]: no method named `lines` found for type `std::io::StdinLock<'_>` in the current scope
 --> src/main.rs:9:32
9 |     for line in stdin().lock().lines() {
  |                                ^^^^^ method not found in `std::io::StdinLock<'_>`
  = help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
1 | use std::io::BufRead;

now follows is my entire file:

use std::io::stdin;
use std::io::prelude::*; // why the need for this?

type Lines = Vec<String>;

pub fn read_input() -> Lines {
    let mut lines:Lines = Vec::new();
    for line in stdin().lock().lines() {
        match line {
            Ok(line) => lines.push(line),
            Err(error) => println!("{:?}", error)
    return lines

fn main() {
    let lines:Lines = read_input();
    println!("{:#?}", lines)

The lines() method comes from the BufRead trait, so you need to import that trait to call the method. You can either do this, as the compiler message suggests:

use std::io::BufRead;

Or you can use the prelude, which is a just a convenient way to import four traits at once.

nice thanks for the quick response. sorry did not notice the hint from the compiler :smiley:

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.