Basic Syntax and Data Types
Understand fundamental Rust syntax, including variables, data types (integers, floats, booleans, characters), and comments.
Rust Programming: Basic Syntax and Data Types
Rust: Basic Syntax and Data Types
Basic Syntax
Rust's syntax borrows heavily from C and C++, but with significant improvements to memory safety and overall design.
- Statements: Most lines of Rust code are statements and end with a semicolon (
;
). - Blocks: Code is often organized into blocks enclosed in curly braces
{}
. Blocks define a scope for variables. - Keywords: Rust uses keywords like
fn
(function),let
(variable declaration),if
,else
,loop
, etc. - Functions: Defined using the
fn
keyword. Themain
function is the entry point of a Rust program. - Comments: Single-line comments start with
//
. Multi-line comments are enclosed in/* */
.
Data Types
Rust is a statically typed language, meaning the type of each variable must be known at compile time. However, Rust often uses type inference, so you don't always have to explicitly declare the type.
Integers
Integers represent whole numbers without fractional parts. Rust provides signed (i
) and unsigned (u
) integer types of various sizes:
i8
,i16
,i32
,i64
,i128
: Signed integers (can be positive or negative).u8
,u16
,u32
,u64
,u128
: Unsigned integers (always non-negative).isize
,usize
: Integers whose size depends on the architecture of the computer (32-bit or 64-bit).i32
is the default integer type when not specified.
Example:
let x: i32 = 10; // Explicitly specify i32
let y = 20; // Type is inferred as i32
let z: u64 = 100; // Explicitly specify u64
Floating-Point Numbers
Floating-point numbers represent numbers with fractional parts.
f32
: Single-precision floating-point number.f64
: Double-precision floating-point number (the default).
Example:
let pi = 3.14159; // Type is inferred as f64
let radius: f32 = 5.0; // Explicitly specify f32
Booleans
Booleans represent truth values: true
or false
.
Example:
let is_valid = true;
let is_finished: bool = false;
Characters
Characters represent Unicode Scalar Values, which include ASCII characters and much more. They are enclosed in single quotes.
Example:
let letter = 'a';
let emoji = '?'; // Crabby
Variables
Variables in Rust are immutable by default. You must use the mut
keyword to make a variable mutable.
Example:
let x = 5; // Immutable variable
// x = 6; // Error! Cannot reassign to immutable variable
let mut y = 10; // Mutable variable
y = 11; // OK
Comments
Comments are used to explain code and are ignored by the compiler.
- Single-line comments:
// This is a single-line comment
- Multi-line comments:
/* This is a multi-line comment */
// This is a single-line comment.
/*
* This is a
* multi-line
* comment.
*/
fn main() {
let x = 10; // Assign the value 10 to x.
println!("The value of x is: {}", x);
}