langShift

Core Syntax and Structure Comparison

Learn the basic syntax of Rust from a JavaScript perspective, including variable declaration, data types, control flow, and function definitions.

Core Syntax and Structure Comparison

📖 Learning Objectives

By comparing the basic syntax of JavaScript and Rust, you will quickly grasp the core concepts of Rust. We will start with the JavaScript syntax you are familiar with and gradually introduce Rust's syntax features.


🎯 Variable Declaration and Scope

JavaScript Variable Declaration

In JavaScript, we use var, let, and const to declare variables:

正在加载...

Rust Variable Declaration

Rust uses the let keyword to declare variables, which are immutable by default:

正在加载...

Key Differences

  1. Default Immutability: Variables in Rust are immutable by default and require the mut keyword to be modified.
  2. Variable Shadowing: Rust allows redeclaring a variable with the same name in the same scope.
  3. Type Inference: The Rust compiler can automatically infer the variable type.

📊 Basic Data Type Comparison

JavaScript Data Types

JavaScript is a dynamically typed language:

正在加载...

Rust Data Types

Rust is a statically typed language, and types are determined at compile time:

正在加载...

Type System Differences

  1. Static vs. Dynamic: Rust checks types at compile time, while JavaScript checks at runtime.
  2. Integer Types: Rust has multiple integer types (i8, i16, i32, i64, u8, u16, u32, u64).
  3. Strings: Rust distinguishes between String (owned) and &str (borrowed).

🔄 Control Flow Comparison

JavaScript Control Flow

正在加载...

Rust Control Flow

正在加载...

Control Flow Differences

  1. if Expression: Rust's if can return a value, making it useful for assignments.
  2. match Statement: More powerful than JavaScript's switch, supporting pattern matching.
  3. Loop Syntax: Rust uses a concise for in syntax.

🏗️ Function Definition Comparison

JavaScript Functions

正在加载...

Rust Functions

正在加载...

Function Differences

  1. Type Annotations: Rust requires explicit type annotations for function parameters and return values.
  2. Return Values: In Rust, the last expression in a function is automatically returned (no return keyword needed, semicolon omitted).
  3. Arrow Functions: Rust does not have an equivalent to JavaScript's arrow functions, but closures serve a similar purpose.

📚 Summary

In this module, we compared the core syntax of JavaScript and Rust. You should now have a basic understanding of:

  • How to declare variables and their immutability in Rust.
  • The differences in basic data types.
  • The powerful control flow structures in Rust like match and if expressions.
  • The syntax for defining functions with explicit types.

Next, we will explore the module systems of both languages.