Rust Notes: Integers and Floats
Published: 2022-02-05
Integers
Integers represent whole numbers. Rust has both unsigned integers and signed integers. unsigned integers cannot be negative, and have a higher positive range than signed integers, that can be negative, but have a lower postive range.
The following table lists the integer literal types in Rust.
The following table lists the formats that are supported for an integer literal definition.
Integer code examples
// i32 by default
let the_answser = 42;
// Annotate the type of integer
let dinner_for_two: i8 = 69;
// Integer suffixing is also supported for type annotation
let its_friday = 420u16; // => 420
// Underscores can help to improve readbility
let you_da_winnah = 1_16_32_5_12_19_40_i64; // => 116325121940Integer Considerations
- i32 is the default type if an integer does not include a type annotation.
- The term u8 and byte are used interchangeably in the Rust community.
- Underscores (_) can be used to improve the readability of an integer literal, they are ignored by the compiler. EG: 1_000_000
Floats
Floating points represent a number with a fractional component expressed in IEEE-754 format. Rust has two floating point types: f32 and f64.
The following table list the floating point literal types and their bits of precision.
Float code examples
// f64 by default
let highly_sexual = 420.69;
// Annotate the type of float
let dinner_for_two: f32 = 69.69;
// Float suffixing is also supported for type annotation
let its_friday = 420.69f32; // => 420.69
// Underscores can help to improve readbility
let you_da_winnah = 420_69.1337_f64; // => 42069.1337Float Considerations
- f64 is the default type if a float does not include a type annotation.
- A float requires a digit before the decimal place (.) in a float definition.
- Underscores (_) can be used to improve the readability of a float literal, they are ignored by the compiler. EG: 420_69.1337
- f64 can be slow on a 32-bit architecture.
Links
https://www.manning.com/books/rust-in-action
https://www.udemy.com/course/ultimate-rust-crash-course/
https://www.techopedia.com/definition/16441/scalar
https://stackoverflow.com/questions/5739888/what-is-the-difference-between-signed-and-unsigned-int