Skip to content

[Coding Guideline] Don't use the isize type #349

@rcseacord

Description

@rcseacord

Exceptions:

FFI is definitely one reason—C's ssize_t maps to isize, and you'll encounter it in POSIX APIs like read() that return -1 on error.
But there are a few other legitimate cases:

  • Pointer arithmetic with negative offsets. If you're doing pointer::offset or working with slices where you need to express "go backwards," isize is the natural type. The offset method takes isize specifically for this reason.
  • Difference between pointers or indices. If you subtract two pointers or two indices, the result can be negative. pointer::offset_from returns isize.
  • Algorithms that use sentinel values. Some algorithms use -1 to represent "not found" or "invalid." While Rust idiomatically uses Option<usize> for this, when porting code or interfacing with such conventions, isize fits naturally.
  • Relative offsets in data structures. If you're implementing something like a self-referential structure with relative pointers, or a compact representation where offsets can be negative, isize makes intent clear.

That said, you're right to reach for usize by default. Most indexing, sizes, and counts are non-negative, and usize makes that invariant explicit. isize is the exception for when you genuinely need signedness at pointer width.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions