3 ms·
No this is not idiomatic Rust code and it's a problem I personally have with a lot of Rust example code. In practice most people would say that you should avoi
by dljsjr 5y ago
No this is not idiomatic Rust code and it's a problem I personally have with a lot of Rust example code.
In practice most people would say that you should avoid using unwrap unless there is absolutely no other way, and in this example you could definitely avoid using unwrap. The code would be a wee bit more verbose but it would be more readable (to me, anyway) and it would avoid a potential crash.
edit to clarify: In Rust, "nulls" and "errors" are part of the type system as structs, with "Option" for nullable types and "Result" for fallible types. "unwrap" is a function that you use if you "know" that the result is 100% not null or an error. Because if you call unwrap on a result that is null or an error, it causes a hard crash. So the only time you use unwrap is if you know you have a situation where a null or an error is unrecoverable and your program should just give up.
This is definitely not one of those cases, which is why unwrap is not idiomatic here. It's the equivalent in Java of an uncaught RuntimeException or an uncaught NPE. And it's setting up newbies for failure when they see this and think that it's The Way™.
- davidkunz 5y agoExactly! Just to add how to deal with Result types in a safer way (as an example): match x { Ok(v) => ..., // doing something with the value v Err(e) => ..., // handling the error e }