-
Notifications
You must be signed in to change notification settings - Fork 32
Open
Description
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::offsetor working with slices where you need to express "go backwards,"isizeis the natural type. The offset method takesisizespecifically for this reason. - Difference between pointers or indices. If you subtract two pointers or two indices, the result can be negative.
pointer::offset_fromreturnsisize. - 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,isizefits 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,
isizemakes 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
Labels
No labels