Skip to content

suggest a.is_multiple_of(b) for a % b == 0 #14289

Closed
@folkertdev

Description

@folkertdev

What it does

suggest that

  • a % b == 0 is rewritten as a.is_multiple_of(b)
  • a % b != 0 is rewritten as !a.is_multiple_of(b)

Advantage

self.is_multiple_of(rhs) is equivalent to self % rhs == 0, except that it will not panic for rhs == 0.
Instead, 0.is_multiple_of(0) == true, and for any non-zero n, n.is_multiple_of(0) == false.

A modulo by zero appears to always panic in rust, and therefore both the method and the expression have a branch. It's just that % will panic, and needs some machinery for that

https://godbolt.org/z/s3j3oKx3T

Drawbacks

it's more characters

Example

const ALIGN: usize = 8

if a % ALIGN == 0 {}

Could be written as:

const ALIGN: usize = 8

if a.is_multiple_of(ALIGN) {}

Metadata

Metadata

Assignees

Labels

A-lintArea: New lints

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions