CommunityNews

CommunityNews

Why Rust should not have provided `unwrap`

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:

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

Most Liked

herbert

herbert

Author of Hands-on Rust

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.

herbert

herbert

Author of Hands-on Rust

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 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.

chikega

chikega

@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?:

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:

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());
}

Popular General Dev topics Top

siddhant3030
I’m thinking of buying a monitor that I can rotate to use as a vertical monitor? Also, I want to know if someone is using it for program...
New
New
AstonJ
We have a thread about the keyboards we have, but what about nice keyboards we come across that we want? If you have seen any that look n...
New
foxtrottwist
Here’s our thread for the Keyboardio Atreus. It is a mechanical keyboard based on and a slight update of the original Atreus (Keyboardio ...
New
AstonJ
Inspired by this post from @Carter, which languages, frameworks or other tech or tools do you think is killing it right now? :upside_down...
New
PragmaticBookshelf
Craft your dream role at work by guiding your manager to take your priorities into account when making decisions. Ken Kousen @kenko...
New
Exadra37
I am thinking in buying one as the second monitor for my Thinkpad while I am travelling: Anyone has experience in using on...
New
AstonJ
This might be my next keyboard (the down arrow on my Apple Magic Keyboard has stopped working :icon_rolleyes:) https://cdn.shopify.com/s...
New
First poster: bot
Raspberry Pi security alarm — the basics. In November last year — I started building a DIY security alarm system, using a Raspberry Pi a...
New
CommunityNews
9 fintech engineering mistakes. Read this list unless you want to build a money dissappearing system
New

Other popular topics Top

Exadra37
I am thinking in building or buy a desktop computer for programing, both professionally and on my free time, and my choice of OS is Linux...
New
Rainer
My first contact with Erlang was about 2 years ago when I used RabbitMQ, which is written in Erlang, for my job. This made me curious and...
New
PragmaticBookshelf
Rust is an exciting new programming language combining the power of C with memory safety, fearless concurrency, and productivity boosters...
New
Exadra37
On modern versions of macOS, you simply can’t power on your computer, launch a text editor or eBook reader, and write or read, without a ...
New
AstonJ
I ended up cancelling my Moonlander order as I think it’s just going to be a bit too bulky for me. I think the Planck and the Preonic (o...
New
PragmaticBookshelf
“Finding the Boundaries” Hero’s Journey with Noel Rappin @noelrappin Even when you’re ultimately right about what the future ho...
New
Exadra37
Oh just spent so much time on this to discover now that RancherOS is in end of life but Rancher is refusing to mark the Github repo as su...
New
AstonJ
If you get Can't find emacs in your PATH when trying to install Doom Emacs on your Mac you… just… need to install Emacs first! :lol: bre...
New
New
husaindevelop
Inside our android webview app, we are trying to paste the copied content from another app eg (notes) using navigator.clipboard.readtext ...
New

Latest in General Dev