to .unwrap() or ?

preview_player
Показать описание
When to use .unwrap() to panic in a Rust program, and when to use ? to handle Results, Options or other errors.
Рекомендации по теме
Комментарии
Автор

It is definitely possible to use ? in tests by returning result, unwrap seems to give more useful error messages.

mattrice
Автор

Thanks for this. I think "how to rust like its python" should be an entry point to the learning process.

dnullify
Автор

Since swift uses a Result<Object, Error> it wasn’t that hard to grasp this concept for me. sort like elixir uses :ok or :error which is probably the easiest in their version of tuples

jaymartinez
Автор

Although ?(try macro) is hard to use. It's generally good manners to use it or .expect method instead of .unwrap() or it's variants. Using ? Will also train you to isolate an error prone value into a function and you are forced to use match which will give you more experience.
So it's the opposite while learning keep using ? And when you are professional enough you can write quick and dirty tests with .unwrap

srivathsansudarsanan
Автор

You said Rust does not use exceptions to handle errors?

What about .expect() all about then? xD

rotteegher
Автор

Why wouldn’t you start with the Result enum and pattern matching?

mba
Автор

".unwrap() models more closely what is true in other languages"
I'd argue, with the exception of C and maybe some lisps, this is simply false. Result/Option are most easily thought of as capturing try/catch blocks in the type system, and thus making it explicit what fucntions can and can't cause issues.
Telling people to start with using .unwrap() may also lead them to not having these types bubble up like they should, which is at best a smell and at worse could lead to the program sliding into a bad state unnoticed (or even crashing).

NekoApril
Автор

This is bad advice.
Enums containing values is one of the core features of rust on should know.
Learn how to use enums and the match statement.
The ? operator is just sytactic sugar.

Pilikio
join shbcf.ru