# Why Rust should not have provided \`unwrap\`

**URL:** <https://forum.devtalk.com/t/why-rust-should-not-have-provided-unwrap/64444>\
**Category:** Backend In The News\
**Tags:** rust\
**Created:** [16 July 2022 13:42 UTC](https://forum.devtalk.com/t/why-rust-should-not-have-provided-unwrap/64444 "2022-07-16T13:42:31Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![CommunityNews](https://forum.devtalk.com/user_avatar/forum.devtalk.com/communitynews/32/1113_2.png) [@CommunityNews](https://forum.devtalk.com/u/CommunityNews)\
**Post date:** [16 July 2022 13:42 UTC](https://forum.devtalk.com/t/why-rust-should-not-have-provided-unwrap/64444/1 "2022-07-16T13:42:31Z")

</div>

> Why Rust should not have provided `unwrap`.  
> I see the unwrap function called a lot, especially in example code, quick-and-dirty prototype code, and code written by beginner Rustaceans. Most of the time I see it, ? would be better and could be used instead with minimal hassle, and the remainder of the time, I would have used expect instead. In fact, I personally never use unwrap, and I even wish it hadn’t been included in the standard library.

Read in full here:

> **[Why Rust should only have provided \`expect\` for turning errors into panics,...](https://www.thecodedmessage.com/posts/2022-07-14-programming-unwrap/)**
>
> UPDATE 2: I have made the title longer because people seem to be insisting on misunderstanding me, giving examples where the only reasonable thing to do is to escalate an Err into a panic. Indeed, such situations exist. I am not advocating for...

_This thread was posted by one of our members via one of our news source trackers._

---

<div class="post-metadata">

**Author:** ![herbert](https://forum.devtalk.com/user_avatar/forum.devtalk.com/herbert/32/1233_2.png) [@herbert](https://forum.devtalk.com/u/herbert)\
**Post date:** [16 July 2022 15:32 UTC](https://forum.devtalk.com/t/why-rust-should-not-have-provided-unwrap/64444/3 "2022-07-16T15:32:01Z")

</div>

`unwrap` is no different than not catching an exception in other languages. It’s handy for those times that you really can’t handle an error (for example, if you’re reading some text from `stdin` in a simple program, you don’t want to try and recover from the OS deciding that console input isn’t available). It’s a conscious decision to crash if something exceptional happens.

I try to encourage people to use `expect`, because it gives a nicer error message.

When you can recover from an error, there are some nicer options. `unwrap_or(default)`, `map` and similar can be nice, quick ways to handle “there isn’t a value here, or something didn’t work”.

The `?` operator is really useful, but _only_ if you are writing a function that returns a `Result`. You can make really nice function chains with `do_this()?.do_that()?` chains - but it only makes sense if you are returning a result _and doing something with it_.

---

<div class="post-metadata">

**Author:** ![chikega](https://forum.devtalk.com/user_avatar/forum.devtalk.com/chikega/32/2473_2.png) [@chikega](https://forum.devtalk.com/u/chikega)\
**Post date:** [20 July 2022 20:07 UTC](https://forum.devtalk.com/t/why-rust-should-not-have-provided-unwrap/64444/4 "2022-07-20T20:07:57Z")

</div>

@herbert Hi Herbert, I’m a big fan of your books and a supporter on Patreon. Would you use .unwrap() or .expect() in [the context of using the `print! vs the `println!` macro?`](https://stackoverflow.com/questions/37531903/how-do-i-print-output-without-a-trailing-newline-in-rust):

Some may not be aware, but using the `print!` (w/o newline) vs `println!` macro, it’s necessary many times to implement `io::stdout().flush()` which will cause many beginner programmer’s eyes to glaze over. It’s probably the reason most introductory tutorials stick with the `println!` macro in order not to overwhelm the beginner programmer. Example use case of printing without a newline:

```auto
use std::io;  
use std::io::stdin;
use std::io::Write; // for .flush()  

fn main() {
    print!("What is your name? ");  
    io::stdout().flush().unwrap(); // or .expect("FAIL!");? here;
    let mut fname = String::new();
    stdin()
        .read_line(&mut fname)
        .expect("Failed to read line");
    
    println!("It's nice to meet you {}!", fname.trim());
}

```

---

<div class="post-metadata">

**Author:** ![herbert](https://forum.devtalk.com/user_avatar/forum.devtalk.com/herbert/32/1233_2.png) [@herbert](https://forum.devtalk.com/u/herbert)\
**Post date:** [20 July 2022 21:21 UTC](https://forum.devtalk.com/t/why-rust-should-not-have-provided-unwrap/64444/5 "2022-07-20T21:21:12Z")

</div>

Hi! Thanks for the support!

That’s a really good question. To auto-flush or not is always a tricky design question (there’s literally decades of discussion in the C world on what to expect). I’d honestly prefer it if there were a flag you could set somewhere to change the behavior to flush after printing.

I’ve used the [macro in this thread](https://internals.rust-lang.org/t/create-a-flushing-version-of-print/9870/4) a couple of times to avoid having to think about it!

In the case of screen output, I think you can safely use `unwrap()`. If `stdout` has gone away, or become unavailable - you potentially have bigger problems to worry about. Unless you’re specifically writing something that _needs_ to worry about it (e.g. you are writing something that needs to keep processing even though the output failed) - I’d keep it simple.

---

<div class="post-metadata">

**Author:** ![chikega](https://forum.devtalk.com/user_avatar/forum.devtalk.com/chikega/32/2473_2.png) [@chikega](https://forum.devtalk.com/u/chikega)\
**Post date:** [23 July 2022 21:45 UTC](https://forum.devtalk.com/t/why-rust-should-not-have-provided-unwrap/64444/6 "2022-07-23T21:45:31Z")

</div>

Thank you for your advice and the link to the macro … good stuff! 🚀

---

<div class="post-metadata">

**Author:** ![OvermindDL1](https://forum.devtalk.com/user_avatar/forum.devtalk.com/overminddl1/32/52_2.png) [@OvermindDL1](https://forum.devtalk.com/u/OvermindDL1)\
**Post date:** [15 September 2022 16:35 UTC](https://forum.devtalk.com/t/why-rust-should-not-have-provided-unwrap/64444/7 "2022-09-15T16:35:05Z")

</div>

This example would be better as:

```nohighlight
use std::io;  
use std::io::stdin;
use std::io::Write; // for .flush()  

pub fn main() -> Result<(), std::io::Error> {
    print!("What is your name? ");  
    io::stdout().flush()?;
    let mut fname = String::new();
    stdin().read_line(&mut fname)?;
    
    println!("It's nice to meet you {}!", fname.trim());
    Ok(())
}

```

Or something that you can add context to like `anyhow` or one of its forks or so.

But yeah, I with we could `#![forbid(unwrap_method)]` or so in our modules to prevent its usage, `expect` is better when you are truly sure that it should never fail.
