Rust integer
Created By: chatGPT
Rust is a systems programming language that provides memory safety without using garbage collection. In Rust, an integer is a data type that represents whole numbers. Rust provides several integer types that include signed and unsigned integers. The signed integers can hold both positive and negative values, while the unsigned integers can only hold zero and positive values.
// Declaring signed integers
let a: i32 = -42;
let b: i64 = 100000;
// Declaring unsigned integers
let c: u32 = 42;
let d: u64 = 100000;
// Declaring a constant integer
const MAX_POINTS: u32 = 100_000;
Rust provides various primitive integer sizes, including i8, i16, i32, i64, and i128, as well as their unsigned counterparts u8, u16, u32, u64, and u128. The size indicates the number of bits used to represent the integer. For instance, i32 is a signed 32-bit integer, while u8 is an unsigned 8-bit integer.
// Different integer types
let small: i8 = -10;
let medium: i32 = 300;
let large: i64 = 123456789;
let very_large: i128 = 123456789012345678901234567890;
let small_unsigned: u8 = 255;
let large_unsigned: u64 = 12345678901234567890;
Type annotations are often necessary in Rust, especially when defining variables. Rust also infers types based on the context, but you can explicitly declare the type to make your code clearer and to avoid unexpected behavior.
// Type inference
let inferred = 42; // i32 inferred
// Explicit type declaration
let explicit: i32 = 42;
You can perform various arithmetic operations on integers in Rust, such as addition, subtraction, multiplication, and division. Keep in mind that division by zero will result in a panic at runtime, so you should always handle potential errors.
// Basic arithmetic operations
let sum = a + b;
let difference = b - a;
let product = a * 2;
let quotient = b / 2; // ensure b is not zero
// Handling potential division by zero
if b != 0 {
let safe_quotient = a / b;
} else {
eprintln!("Error: Division by zero");
}