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
- Default Immutability: Variables in Rust are immutable by default and require the
mut
keyword to be modified. - Variable Shadowing: Rust allows redeclaring a variable with the same name in the same scope.
- 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
- Static vs. Dynamic: Rust checks types at compile time, while JavaScript checks at runtime.
- Integer Types: Rust has multiple integer types (i8, i16, i32, i64, u8, u16, u32, u64).
- Strings: Rust distinguishes between
String
(owned) and&str
(borrowed).
🔄 Control Flow Comparison
JavaScript Control Flow
Rust Control Flow
Control Flow Differences
if
Expression: Rust'sif
can return a value, making it useful for assignments.match
Statement: More powerful than JavaScript'sswitch
, supporting pattern matching.- Loop Syntax: Rust uses a concise
for in
syntax.
🏗️ Function Definition Comparison
JavaScript Functions
Rust Functions
Function Differences
- Type Annotations: Rust requires explicit type annotations for function parameters and return values.
- Return Values: In Rust, the last expression in a function is automatically returned (no
return
keyword needed, semicolon omitted). - 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
andif
expressions. - The syntax for defining functions with explicit types.
Next, we will explore the module systems of both languages.
Introduction to Rust & Environment Setup
Understand Rust from a JavaScript developer's perspective, learn what Rust can do, and how to set up the development environment.
Module System and Build Tools
Learn Rust's module system, package management, and project structure, comparing them with JavaScript's modular development.