Skip to content

Existing rules Do not use integer type as divisor has problems #209

@rcseacord

Description

@rcseacord

There are some problems with this rule. First, I don't understand the title. You can't have integer division?

The examples don't seem to compile. Issues in the code

Missing use statement for std::num::NonZero.

Improper use of match inside if let — the syntax is invalid.

You’re trying to use divisor of type NonZero directly in division — NonZero doesn’t implement Copy or Deref, and you need to access its value.

result is defined twice: once inside the if let and again after. This will cause confusion or a scope error.

Missing semicolon at the end of the second match.

The logic around handling division by zero (from x) is unclear and risky — you try both NonZero::new(x) and checked_rem(x) with x = 0.

Fixed Version of the Program
use std::num::NonZeroU32;

fn main() {
    let x = 0;

    // Safe division using NonZeroU32
    if let Some(nonzero_divisor) = NonZeroU32::new(x) {
        let result = 5 / nonzero_divisor.get();
        println!("Division result: {}", result);
    } else {
        println!("Cannot divide by zero using NonZeroU32.");
    }

    // Safe remainder using checked_rem
    let remainder_result = match 5u32.checked_rem(x) {
        None => 0,
        Some(r) => r,
    };

    println!("Remainder result: {}", remainder_result);
}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions