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

Where Next?

Popular Backend topics Top

First poster: bot
It’s Time to Say Goodbye to Docker. Docker is not the only containerization tool out there and there might just be better alternatives… ...
New
First poster: bot
There is a long, difficult road from vague, pie-in-the-sky ideas about what would be cool to have in a new programming language, to a rob...
New
New
First poster: AstonJ
Pocketlang is a small (~3000 semicolons) and fast functional language written in C. It’s syntactically similar to Ruby and it can be lear...
New
First poster: bot
Why Lisp? A lot of people ask us the question, why do we choose to use Common Lisp as our primary development language? Often times the q...
New
First poster: bot
Where is the Ruby language headed? At RubyConf 2021, the presentations about the language focused on static typing and performance—where ...
New
New
CommunityNews
Avoid Yoda conditions in Perl you should—The Phoenix Trap. Assign not when mean to compare you do. Help you warnings and strictures can.
New
First poster: bot
For the first 8 or so years of my programming experience, while I was an undergraduate and later graduate student, working in the experim...
New
First poster: OvermindDL1
GitHub - deadpixi/wasm-maze-generator: A simple WASM maze generator in Go. A simple WASM maze generator in Go. Contribute to deadpixi/wa...
New

Other popular topics Top

ohm
Which, if any, games do you play? On what platform? I just bought (and completed) Minecraft Dungeons for my Nintendo Switch. Other than ...
New
axelson
I’ve been really enjoying obsidian.md: It is very snappy (even though it is based on Electron). I love that it is all local by defaul...
New
dasdom
No chair. I have a standing desk. This post was split into a dedicated thread from our thread about chairs :slight_smile:
New
Margaret
Hello content creators! Happy new year. What tech topics do you think will be the focus of 2021? My vote for one topic is ethics in tech...
New
Rainer
Not sure if following fits exactly this thread, or if we should have a hobby thread… For many years I’m designing and building model air...
New
PragmaticBookshelf
Learn different ways of writing concurrent code in Elixir and increase your application's performance, without sacrificing scalability or...
New
DevotionGeo
The V Programming Language Simple language for building maintainable programs V is already mentioned couple of times in the forum, but I...
New
Margaret
Hello everyone! This thread is to tell you about what authors from The Pragmatic Bookshelf are writing on Medium.
1142 25765 758
New
First poster: joeb
The File System Access API with Origin Private File System. WebKit supports new API that makes it possible for web apps to create, open,...
New
CommunityNews
A Brief Review of the Minisforum V3 AMD Tablet. Update: I have created an awesome-minisforum-v3 GitHub repository to list information fo...
New