Function does not work

pWorking on the same example beginner code as in my last post in help, I decided to create a function which reads yes/no from the console and outputs true/false:

fn bool_from_yesno() -> bool {
	let mut yes_no = String::new();
	io::stdin().read_line(&mut yes_no).expect("error reading the line!");
	match yes_no.as_str() {
		"yes" => true,
		"no" => false,
		_ => false,
	}
}

Now at first it looks okay to me, however it only outputs false. In so far I most likely made an beginner error.

read_line will include the newline character in the data that it reads, but your match arms don't include one (so you're always getting the _ case). You'll probably want to match on yes_no.trim() instead.

If you want to see this newline, try printing out the string:

	io::stdin().read_line(&mut yes_no).expect("error reading the line!");
	dbg!(&yes_no);

Nothing wrong with some good 'ol print debugging.

Thanks for your replies, trim() solved the case.

One wish for a tutorial book is being that this is elaborated on as on google the as_str() function pops up first when inputting "String to string literal".

as_str() takes a &String and gives you a &str. (doc)
trim() takes a &str and gives you a trimmed &str. (doc)

Both as_str() and trim() return a &str. You could write your match two different ways here:

	match yes_no.trim() {          // Version 1
	match yes_no.as_str().trim() { // Version 2
    // They're functionally identical.

Why can you do this? The answer is a feature called "Deref Coercion" that you'll learn about in chapter 15.

1 Like