Blog Series: From TypeScript to Rust & Go — Day 2: Exploring Basic Syntax and Concepts
Day 2: Diving into Rust and Go Basics — Variables, Data Types, and Control Flow
Introduction
Welcome back to Day 2 of our journey from TypeScript to Rust and Go! Now that we’ve set up our environments and explored “Hello World” in both languages, it’s time to dive into the basics.
Today’s Objectives:
- Understand Rust and Go’s approach to variables, data types, and control flow.
- Highlight similarities to TypeScript for a smoother transition.
- Get hands-on with coding examples in both languages to see these basics in action.
1. Variables and Data Types
Variables are the building blocks of any language. Both Rust and Go have clear syntax for declaring variables, with a few key differences from TypeScript.
Rust Variables and Data Types
In Rust:
- Variables are immutable by default, which means you can’t change their value once they’re set.
- To create a mutable variable, you need to use the
mut
keyword. - Rust has strict typing, which means you usually need to declare the type of each variable.
Basic Variable Declaration in Rust:
// Immutable variable (default)
let name = "Alice";
// Mutable variable
let mut age = 30;
// Explicit type declaration
let is_active: bool = true;
Rust’s strong type system may remind you of TypeScript’s type-checking, though with Rust, this is enforced at compile time for performance and safety.
Go Variables and Data Types
In Go:
- Variables are mutable by default, so you don’t need a keyword like
mut
. - Go is also statically typed, but its syntax is more concise, often inferring types automatically.
Basic Variable Declaration in Go:
// Declare a variable with inferred type
name := "Alice"
// Declare with explicit type
var age int = 30
// Boolean variable
var isActive bool = true
Tip for TypeScript Developers: Rust’s explicit type annotations are similar to TypeScript’s, but Go’s syntax is closer to JavaScript’s, with simpler variable declarations.
2. Control Flow — Conditionals and Loops
Control flow statements allow us to manage program execution based on conditions. Both Rust and Go have if
statements, but their syntax and behavior have subtle differences.
Conditionals in Rust
Rust requires explicit bool
types in if
statements. The syntax is straightforward:
let age = 20;
if age >= 18 {
println!("You are an adult.");
} else {
println!("You are a minor.");
}
Conditionals in Go
In Go, if
statements are similar, but Go also allows you to declare variables within if
statements, which can be helpful for scoping:
age := 20
if age >= 18 {
fmt.Println("You are an adult.")
} else {
fmt.Println("You are a minor.")
}
Notable Difference: Unlike JavaScript and TypeScript, neither Rust nor Go allows truthy/falsy values in conditionals. This means that only explicit boolean values (true
or false
) can be used in conditions.
3. Loops in Rust and Go
Both languages support looping, but their approaches are a bit different.
Loops in Rust
Rust has three main types of loops: loop
, while
, and for
.
- Loop: This is an infinite loop, useful when you want to create a loop that only breaks under certain conditions.
- While Loop: Similar to JavaScript/TypeScript, it runs as long as the condition is true.
- For Loop: Rust’s
for
loop is similar tofor…of
in JavaScript.
Example of Each Loop Type in Rust:
// Infinite loop
let mut count = 0;
loop {
count += 1;
if count == 5 {
break;
}
}
// While loop
let mut number = 0;
while number < 5 {
println!("Number is: {}", number);
number += 1;
}
// For loop
for i in 0..5 {
println!("i is: {}", i);
}
Loops in Go
Go has only one loop keyword: for
. It handles everything from traditional loops to infinite loops.
Examples of for
Loops in Go:
// Traditional for loop
for i := 0; i < 5; i++ {
fmt.Println("i is:", i)
}
// While-style loop
count := 0
for count < 5 {
fmt.Println("Count is:", count)
count++
}
// Infinite loop
for {
fmt.Println("This will run forever!")
break // Add a break to avoid an infinite loop
}
Tip for TypeScript Developers: Rust’s for
loop syntax may feel familiar because it resembles TypeScript’s for…of
loop, whereas Go’s single for
keyword handles everything.
5. Hands-On Practice: Building a Simple Temperature Converter
Let’s apply what we’ve learned by creating a basic temperature converter in both languages. This program will convert Celsius to Fahrenheit and vice versa.
Rust Code:
fn main() {
let celsius = 25.0;
let fahrenheit = celsius_to_fahrenheit(celsius);
println!("{}°C is equal to {}°F", celsius, fahrenheit);
}
fn celsius_to_fahrenheit(celsius: f64) -> f64 {
(celsius * 9.0/5.0) + 32.0
}
Go Code:
package main
import "fmt"
func main() {
celsius := 25.0
fahrenheit := celsiusToFahrenheit(celsius)
fmt.Printf("%.2f°C is equal to %.2f°F\n", celsius, fahrenheit)
}
func celsiusToFahrenheit(celsius float64) float64 {
return (celsius * 9.0 / 5.0) + 32.0
}
Explanation: This example demonstrates:
- Functions: Defined similarly to TypeScript, each function has a return type.
- Data Types: Both Rust and Go have strict typing, especially for function parameters and returns.
6. Day 2 Homework
Practice these concepts with a few challenges:
- Variable Practice: Create variables of each type (integer, float, boolean, string) in Rust and Go.
- Control Flow: Write a program in Rust and Go that uses conditionals to check if a number is even or odd.
- Loop Practice: Write a loop in both languages that prints numbers from 1 to 10, but skips 5.
7. Next Time: Functions and Error Handling
In our next post, we’ll explore functions, scopes, and error handling. These are crucial as we start building more complex applications. Understanding how errors are managed in Rust and Go will help us write robust, production-ready code.