Rust is a systems programming language that emphasizes safety and performance. Understanding its basic syntax is crucial for writing efficient and effective code. In this article, we will explore three practical examples of basic syntax in Rust that will help you get started on your programming journey.
The classic first program in any programming language is the “Hello, World!” example. This simple program demonstrates how to print text to the console.
fn main() {
println!("Hello, World!");
}
In this example, fn
defines a function. main
is the entry point of the program, and println!
is a macro that prints the text to the console. The exclamation mark indicates that it’s a macro, not a regular function.
println!
line, as Rust requires it.Variables in Rust are immutable by default, which means once a variable is assigned a value, it cannot be changed unless explicitly declared mutable. This example shows how to define variables and display their values.
fn main() {
let name = "Taylor"; // Immutable variable
let mut age = 30; // Mutable variable
println!("Name: {}", name);
println!("Age: {}", age);
age += 1; // Incrementing age
println!("Next Year Age: {}", age);
}
In this example, we define an immutable variable name
and a mutable variable age
. We then print their values and demonstrate how to change the mutable variable.
let mut
to declare a mutable variable.{}
in the println!
macro are placeholders that will be replaced with the variable values.Control flow is essential for making decisions in your code. This example illustrates how to use if
statements to control the execution flow based on conditions.
fn main() {
let number = 10;
if number < 5 {
println!("The number is less than 5.");
} else if number == 10 {
println!("The number is exactly 10.");
} else {
println!("The number is greater than 5 and not 10.");
}
}
In this example, we check the value of number
and print different messages based on its value. The if
, else if
, and else
statements allow for multiple conditions to be checked.
else if
branches as necessary.By understanding these basic syntax examples in Rust, you will build a solid foundation for your programming journey. Happy coding!