Basic Syntax in Rust: 3 Practical Examples

Explore essential examples of basic syntax in Rust to kickstart your programming journey.
By Taylor

Introduction to Basic Syntax in Rust

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.

Example 1: Hello, World!

Context

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.

Notes

  • You can modify the text inside the quotes to print anything you like.
  • Make sure to include the semicolon at the end of the println! line, as Rust requires it.

Example 2: Variables and Data Types

Context

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.

Notes

  • Use let mut to declare a mutable variable.
  • The curly braces {} in the println! macro are placeholders that will be replaced with the variable values.

Example 3: Control Flow with Conditionals

Context

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.

Notes

  • You can add as many else if branches as necessary.
  • Rust requires that conditions are enclosed in parentheses, but the blocks of code do not need to be.

By understanding these basic syntax examples in Rust, you will build a solid foundation for your programming journey. Happy coding!