liveBook · Manning

Integer

As explained in Learn Rust in a Month of Lunches

An integer is a whole-number numeric value without a fractional part.

An integer is a whole number with no decimal point. In Rust, integers are primitive types: basic building blocks for values such as 8, −8, and 0. Add a decimal point and Rust treats the number as a different kind of type, a float. section 1.3 section 1.4

Choose an integer type by asking two questions:

  • Could the value be negative? Signed types can hold negative values, zero, and positive values; unsigned types hold only nonnegative values. section 1.3
  • How large might it be? The number in a type name gives its bit width: u8 has 8 bits and can hold values up to 255; u16 can hold values up to 65,535. Bits store binary digits, each either 0 or 1. section 1.3

Let Rust infer a type—or choose one

In `let my_number = 8;`, Rust chooses `i32`. To choose a different type, write `let my_number: u8 = 8;` or put the type on the number: `let my_number = 8u8;`. Underscores can make a large number easier to read, as in `100_000_000_i32`; they do not change its value. section 1.4

error[E0604]: only u8 can be cast as char, not i32
 --> src\main.rs:3:20
  |
3 |     println!("{}", my_number as char);
  |                    ^^^^^^^^^^^^^^^^^

A compiler error shows why the precise integer type can matter: an inferred `i32` cannot be cast directly to `char` this way; the example requires `u8`. section 1.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains signedness, bit widths, binary, and type inference, but does not develop integer arithmetic.
Examples
Shows signed values, u8 and u16 limits, annotated and suffixed literals, and a rejected i32-to-char cast.
What it assumes
Introduces primitive types, signedness, bits, and type inference in plain language.
What you can do after
Apply it in Rust by choosing signedness and bit width, accepting inferred i32, or specifying another integer type.
How it connects
Connects integers to binary, bits, type inference, floats, character casts, and compiler errors.

Also explained in

Compare how 15 books explain integer →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.