Rust data types
Created By: chatGPT
Rust is a systems programming language that focuses on speed, memory safety, and parallelism. One of its core features is its rich range of data types. Understanding these data types is essential for writing efficient and safe Rust code. Below are the primary categories of data types in Rust.Scalar Types represent a single value. Rust has four primary scalar types:
Integer Types: These can be signed or unsigned and come in different sizes (e.g., 8, 16, 32, 64 bits). Here’s how you can declare an integer variable:
let a: i32 = 10; // Signed 32-bit integer
let b: u32 = 20; // Unsigned 32-bit integer
Floating-Point Types: Rust supports two floating-point types: f32 and f64. Example:
let x: f64 = 3.14; // 64-bit floating point
let y: f32 = 2.71; // 32-bit floating point
Boolean Type: This type can hold either
true
or false
. Example:let is_active: bool = true;
Character Type: This type represents a single Unicode character. Example:
Compound Types can group multiple values together. They include tuples and arrays.let c: char = 'A';
Tuples: Tuples can hold a fixed number of elements with different types. You can create a tuple like this:
let tuple: (i32, f64, char) = (42, 3.14, 'x');
Arrays: Arrays are collections of elements of the same type with a fixed size. You can declare an array as follows:
Rust also includes strings, which are collections of UTF-8 bytes. There are two main string types: let array: [i32; 5] = [1, 2, 3, 4, 5];
String
and &str
.You can create a mutable
String
like this:let mut s: String = String::from("Hello");
And you can create a string slice, which is an immutable reference to a string:
In summary, Rust's data types are essential for writing safe and performant code, making it a powerful choice for system-level programming. Experimenting with these types will deepen your understanding of the language.let slice: &str = "World";