Learn Nim - Official Tutorial (Dark Theme)

Welcome to the Nim Tutorial

This interactive tutorial will guide you through the basics of the Nim programming language. By the end, you'll have a solid foundation to start building your own Nim projects.

1. Hello, World!

Let's start with the classic "Hello, World!" program:

echo "Hello, World!"

This simple line prints "Hello, World!" to the console. In Nim, you don't need semicolons at the end of statements.

Exercise 1:

Modify the program to print your name instead of "World".

2. Variables and Types

Nim uses type inference, but you can also explicitly declare types:

var
  name: string = "Alice"
  age: int = 30
  height: float = 1.75
  isStudent: bool = true

echo "Name: ", name
echo "Age: ", age
echo "Height: ", height
echo "Is student: ", isStudent

Tip: Use let for immutable variables and var for mutable ones.

3. Control Structures

Nim supports familiar control structures:

let x = 10

if x > 5:
  echo "x is greater than 5"
elif x == 5:
  echo "x is equal to 5"
else:
  echo "x is less than 5"

for i in 1..5:
  echo i

var j = 0
while j < 5:
  echo j
  inc j

4. Functions

Functions in Nim are defined using the proc keyword:

proc greet(name: string): string =
  return "Hello, " & name & "!"

echo greet("Bob")

# You can omit the return statement for the last expression
proc add(a, b: int): int =
  a + b

echo add(5, 3)

Exercise 2:

Write a function that calculates the area of a rectangle given its width and height.

5. Collections

Nim provides several collection types, including sequences and arrays:

# Sequence (dynamic array)
var fruits: seq[string] = @["apple", "banana", "cherry"]
fruits.add("date")

# Array (fixed size)
var numbers: array[5, int] = [1, 2, 3, 4, 5]

echo fruits
echo numbers

This is just the beginning of what Nim has to offer. Continue exploring topics like object-oriented programming, generics, and metaprogramming to unlock Nim's full potential!