Hone logo
Hone
Problems

Robust Option Handling in Rust

In Rust, Option<T> is a fundamental enum used to represent a value that may or may not be present. Mastering its usage is crucial for writing safe, idiomatic, and bug-free Rust code, especially when dealing with data that might be missing or operations that could fail. This challenge focuses on implementing a common pattern: safely extracting and processing a value from an Option, providing a default if the value is absent.

Problem Description

Your task is to write a Rust function that takes an Option<i32> as input. This function should attempt to extract the i32 value if it's present (Some(value)). If the Option is None, the function should gracefully handle this absence by returning a predefined default value.

Specifically, you need to:

  1. Define a function that accepts an Option<i32>.
  2. Implement logic within the function to check if the Option contains a value.
  3. If a value is present, return that value.
  4. If the Option is None, return a specific default integer value. For this challenge, the default value should be 0.
  5. The function should return an i32.

Consider the implications of both Some and None variants of Option<i32>.

Examples

Example 1:

Input: Some(42)
Output: 42
Explanation: The input Option contains a value (42), so that value is returned.

Example 2:

Input: None
Output: 0
Explanation: The input Option is None, so the default value of 0 is returned.

Example 3:

Input: Some(-10)
Output: -10
Explanation: The input Option contains a value (-10), so that value is returned.

Constraints

  • The input will always be of type Option<i32>.
  • The output will always be of type i32.
  • The default value to be returned when the input is None is 0.
  • Your solution should be efficient and idiomatic Rust.

Notes

Rust provides several powerful methods on Option for handling these scenarios. Think about how you can leverage these methods to create a concise and expressive solution. Common approaches include pattern matching (match) and specific Option combinator methods. Consider which approach best suits the clarity and simplicity required for this problem.

Loading editor...
rust