Rust Programming Syntax and Concepts: A Comprehensive Example

Table of Contents

Background

Example

  use std::io;

  fn main() {
      // example
      println!("Guess the number!");

      println!("Please input your guess.");

      let mut guess = String::new();

      io::stdin().read_line(&mut guess)
          .expect("Failed to read line");

      println!("You guessed: {}", guess);
      // bindings
      let (x, y) = (1, 2);
      // mutability
      let mut z = 5;
      z = 10;

       {
          let y: i32 = 3;
          println!("The value of x is {} and value of y is {}", x, y);
       }
      // functions
      fn print_sum(x, y) {
          println!("sum is: {}", x + y);
      }
      // loops
      while !done {
          x += x - 3;

          println!("{}", x);

          if x % 5 == 0 {
              done = true;
          }
      }
      // borrowing
      fn foo(v1: &Vec<i32>, v2: &Vec<i32>) -> i32 {
          // do stuff with v1 and v2

          // return the answer
          42
      }

      let v1 = vec![1, 2, 3];
      let v2 = vec![1, 2, 3];
      let answer = foo(&v1, &v2);
      // node interop
      fn fibonacci(x: i32) -> i32 {
          if x <= 2 {
              return 1;
          } else {
              return fibonacci(x - 1) + fibonacci(x - 2);
          }
      }
  }

Syntax

Concepts

  • Mutability
  • Types
    • Primitives
    • Structs
    • Enums
  • Scope
    • Closure
    • Shadowing
  • References and borrowing
  • Pattern matching
  • Overloading
  • Package management
  • Building
  • Deployment
  • Dependencies

Tutorials

Author: Jason Walsh

j@wal.sh

Last Updated: 2024-08-14 06:08:50