Hone logo
Hone
Problems

Safe Division with Option Handling in Rust

This challenge focuses on implementing a safe division function in Rust using the Option type. Division by zero is a common error, and Rust's Option type provides a robust way to handle this potential failure gracefully, returning None when division by zero occurs and Some(result) when the division is successful. This exercise will reinforce your understanding of Option and error handling in Rust.

Problem Description

You are tasked with creating a function safe_divide that takes two integers, numerator and denominator, as input and returns an Option<i32>. The function should perform integer division of the numerator by the denominator.

  • What needs to be achieved: Implement a function that safely divides two integers, handling the case where the denominator is zero.
  • Key requirements:
    • The function must return None if the denominator is zero.
    • If the denominator is not zero, the function must return Some(numerator / denominator).
    • The return type must be Option<i32>.
  • Expected behavior: The function should correctly perform integer division when the denominator is non-zero and gracefully handle division by zero by returning None.
  • Edge cases to consider:
    • denominator is zero.
    • numerator is zero.
    • Large values for numerator and denominator that could potentially lead to overflow (though overflow is not the primary focus of this challenge, consider it).

Examples

Example 1:

Input: numerator = 10, denominator = 2
Output: Some(5)
Explanation: 10 divided by 2 is 5. The result is wrapped in Some().

Example 2:

Input: numerator = 5, denominator = 0
Output: None
Explanation: Division by zero is not allowed. The function returns None.

Example 3:

Input: numerator = 0, denominator = 5
Output: Some(0)
Explanation: 0 divided by 5 is 0. The result is wrapped in Some().

Example 4:

Input: numerator = -10, denominator = 2
Output: Some(-5)
Explanation: -10 divided by 2 is -5. The result is wrapped in Some().

Constraints

  • numerator and denominator are integers (i32).
  • The function must return an Option<i32>.
  • The function should be efficient and avoid unnecessary computations.
  • While overflow is a consideration, the primary focus is on handling division by zero.

Notes

  • Rust's Option type is a powerful tool for handling potentially missing values. Think about how Option naturally represents the possibility of division by zero.
  • Consider using a simple if statement to check for the division by zero condition.
  • Remember that integer division in Rust truncates towards zero.
Loading editor...
rust