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

First poster: HenryCost
I wired my tree with 500 LED lights and calculated their 3D coordinates… If you support me on Patreon at any point in December 2020 I wi...
New
New
First poster: bot
Flipper Zero is a portable multi-tool for pentesters and geeks in a toy-like body. It loves hacking digital stuff, such as radio protocol...
New
First poster: bot
The overengineered Solution to my Pigeon Problem. TL;DR: I built a wifi-equipped water gun to shoot the pigeons on my balcony, controlle...
New
First poster: bot
Developing Godot Projects with Neovim. When I started using Godot Engine, what surprised me the most is the built-in Language Server Pro...
New
First poster: Maartz
Apple’s taken the joy out of its Books app with iOS 16. The lovely page flip is gone.
New
First poster: dyowee
Rust: The wrong people are resigning. Rust: The wrong people are resigning. GitHub Gist: instantly share code, notes, and snippets.
New
First poster: KnowledgeIsPower
Building a Slack/Discord alternative with Tauri/Rust linen <span class="hashtag-icon-placeholder"></span>blog. Introduction My name is K...
New
First poster: AstonJ
Jan | Rethink the Computer. Jan turns your computer into an AI machine by running LLMs locally on your computer. It’s a privacy-focus, l...
New
CommunityNews
We’re a tiny team @deepseek-ai pushing our limits in AGI exploration. Starting this week , Feb 24, 2025 we’ll open-source 5 repos – one ...
New

Other popular topics Top

New
AstonJ
Curious to know which languages and frameworks you’re all thinking about learning next :upside_down_face: Perhaps if there’s enough peop...
New
AstonJ
In case anyone else is wondering why Ruby 3 doesn’t show when you do asdf list-all ruby :man_facepalming: do this first: asdf plugin-upd...
New
PragmaticBookshelf
“A Mystical Experience” Hero’s Journey with Paolo Perrotta @nusco Ever wonder how authoring books compares to writing articles?...
New
wmnnd
Here’s the story how one of the world’s first production deployments of LiveView came to be - and how trying to improve it almost caused ...
New
gagan7995
API 4 Path: /user/following/ Method: GET Description: Returns the list of all names of people whom the user follows Response [ { ...
New
Maartz
Hi folks, I don’t know if I saw this here but, here’s a new programming language, called Roc Reminds me a bit of Elm and thus Haskell. ...
New
foxtrottwist
A few weeks ago I started using Warp a terminal written in rust. Though in it’s current state of development there are a few caveats (tab...
New
PragmaticBookshelf
A Ruby-Centric Chat with Noel Rappin @noelrappin Once you start noodling around with Ruby you quickly figure out, as Noel Rappi...
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