Rust Syntax
Rust's syntax combines the clarity of high-level languages with the performance and safety of low-level languages. It is designed to be readable, safe, and powerful.
Basic Syntax
Rust syntax resembles C++ but adds modern language features such as type inference and pattern matching.
fn main() { println!("Hello, world!"); }
Variables and Mutability
Variables are immutable by default in Rust. To make them mutable, the mut
keyword is used.
let x = 5; // Immutable variable let mut y = 10; // Mutable variable y = 15; // This is allowed
Data Types
Rust supports many data types, including primitive types like integers, floating-point numbers, booleans, and character, as well as compound types like arrays and tuples.
let a1: i32 = 42; // Signed 32-bit integer let at2: f64 = 3.1415; // Floating-point number let at3: bool = true; // Boolean let at4: char = 'a'; // Character let array: [i32; 3] = [1, 2, 3]; // Array let tuple: (i32, f64, &str) = (1, 3.14, "string"); // Tuple
Control Flow
Rust supports traditional control flow structures such as if, for, while
and match
.
let condition = true; if condition { println!("Condition was true!"); } else { println!("Condition was false!"); } for number in 1..4 { println!("Number: {}", number); }
Functions
In Rust, functions are defined using the fn
keyword. Functions can return values using the >
syntax.
fn add(a: i32, b: i32) -> i32 { a + b } fn main() { let result = add(5, 3); println!("The sum is: {}", result); }
Comments
Rust supports both single-line and multiline comments:
// This is a single-line comment /* This is a multiple-line comment */
Ownership and Borrowing
Rust's unique approach to memory safety relies on ownership and borrowing. Variables have ownership of values they point to, and values are destroyed when the owner goes out of scope. Values can be borrowed either immutably or mutably using references.
let s1 = String::from("hello"); let s2 = s1; // Move: Ownership转移到 s2 println!("{}", s1); // This will cause an error
To prevent the above error, you can use clones to copy the data or borrow it:
let s1 = String::from("hello"); let s2 = s1.clone(); // Clone the data println!("s1: {}, s2: {}", s1, s2);
References and Borrowing
Rust provides references for borrowing data without