Don't say anyway, say anyhow

you are viewing a single comment's thread
view the rest of the comments
[–] 35 points 1 year ago (9 children)

Unwrap means it forces to evaluate the result as an ”ok value”. If it’s an ”error value”, it will crash. It’s a bad practice to rely on it, as it’s one of the most common ways a Rust programs can crash.

Rust offers many options to handle errors that don’t risk crashing. For example, unwrap_or_default, which means ”if it’s an error value, use the default value for this type, such as 0 for integers”

  • source
  • parent
  • hideshow 9 child comments
  • [–] 15 points 1 year ago (5 children)

    I mean using unwrap is not bad practice if the value is guaranteed to not be none, which can happen frequently in some applications.

  • source
  • parent
  • hideshow 5 child comments
  • [–] 4 points 1 year ago* (3 children)

    If it's guaranteed to not be None, why is it an Option?

  • source
  • parent
  • hideshow 3 child comments
  • [–] 2 points 1 year ago*

    Oh, it can happen when you do calculations with compile-time constants...

    But the GP's claim that it's a "frequent" thing is suspect.

    (Crashing is also useful when you are writing and-user applications, but you'll probably want .expect like in the meme.)

  • source
  • parent
  • [–] 1 point 1 year ago

    A very typical use-case would be getting something from a HashMap (or a Vector) and calling unwrap because you know it must exist (as you got a reference to the index or object that must be valid in the HashMap or Vector).
    Or if you call a function that returns Option<…> depending on the current state and you know that it must return Some(…) in the current situation.

  • source
  • parent
  • [–] 7 points 1 year ago* (1 child)

    Unwrap is good for prototyping and trying out stuff fast, but it generally shouldn't make it past a code review onto main, unless you're very sure

  • source
  • parent
  • hideshow 1 child comment