Hello World in Nim
Your first Nim program - the classic Hello World example with Docker setup
Every programming journey starts with Hello World. Let’s write our first Nim program.
The Code
Create a file named hello.nim:
| |
That’s it! If you know Python, this looks very familiar - and that’s by design.
Understanding the Code
echo- Prints values to standard output followed by a newline"Hello, World!"- A string literal enclosed in double quotes- No parentheses required - Nim allows calling procedures without parentheses
- No main function - Top-level code runs automatically
Running with Docker
The easiest way to run this without installing Nim locally:
| |
Running Locally
If you have Nim installed:
| |
Expected Output
Hello, World!
Key Concepts
- Python-like syntax - Clean, readable code without excessive punctuation
- Compiled language - Despite the scripting feel, Nim compiles to efficient native code
nim c- Compiles to C backend (default)-rflag - Run the compiled binary immediately after compilation- No boilerplate - Jump straight to writing code
Understanding Compilation
Nim compiles through an intermediate step:
| |
This two-stage compilation lets Nim leverage decades of C compiler optimizations.
A More Detailed Version
For a slightly more structured approach showing Nim’s type system:
| |
This version demonstrates:
- Procedure definition - Using
procwith type annotations - Type annotations -
name: stringand return type: string - String concatenation - Using the
&operator resultvariable - Nim’s implicit return variableletbinding - Immutable variable declaration
Object-Oriented Approach
Nim supports object-oriented programming:
| |
Key features shown:
typesection - Defines custom typesobjecttype - Nim’s structure/record type- Constructor pattern -
newGreeterreturns an initialized object - Method syntax -
greeter.greet()is syntactic sugar forgreet(greeter)
Compilation Options
Nim offers various compilation modes:
| |
Multiple Output Formats
Nim can compile to different backends:
| |
The JavaScript target creates hello.js that runs in browsers or Node.js.
Why Nim Stands Out
Coming from other languages, you’ll notice Nim’s unique characteristics:
- Python syntax, C speed - Write readable code that runs fast
- Multiple backends - One codebase, multiple targets (C, C++, JS)
- Powerful metaprogramming - Macros that operate on the AST
- Modern memory management - ORC provides deterministic destruction
Next Steps
Continue to Variables and Data Types to learn about Nim’s powerful type system, including distinct types, type inference, and the let/var/const distinction.
Running Today
All examples can be run using Docker:
docker pull nimlang/nim:alpine