First question: a "function" to replace io::stdin().read_line(&mut variable) boilerplate code

Should be pretty basic stuff:

Well starting my coding session today I tried to code an employe expample with a structure with name(string), age(u32), year_salary(f64), company_car(bool) in it.

To get the data with input I only know io::stdin().read_line() and eventual parsing (so I didn't look up if this works with bool variable type)

Now with above the code would end up pretty boilerplate by writing something like:

let mut name = String::new()
io::stdin().readline(&mut name). expect("Error reading the line!");

four times below each other.

So I went with following preliminary:

fn readln(mut entry: &mut String) -> &mut String{
io::stdin().read_line(&mut entry).expect("Error reading the line!");
entry

}

which still looks inefficient to me.

So I did another coding over it and arrived at:

fn readln() -> String{
let mut entry = String::new();
io::stdin().read_line(&mut entry).expect("Error reading the line!");
entry

}

So my question is, is there a more efficient or shorter code for a function that reads in a line entered in the console and puts it in a variable?

Your last version looks pretty good to me. Here’s one possible alternative:

use std::io::{stdin, BufRead};

pub fn readln() -> String {
    stdin().lock().lines().next().expect("end of input").expect("error reading from stdin")
}

There's a slight difference in behavior: Your versions using read_line will return a string that includes the trailing newline character(s), while my version using lines() will return a string without any newlines.

There's also the read_input crate for quickly getting user input from the standard input generically.

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.