Nim Syntax
Page bookmarks:
Hello World!
Let's honor a tradition. In most languages you must write several lines of code to display a message. In Nim one single line of code is good enough:
echo ("hello world")
Try it: play.nim-lang.org
Note: Nim is compile into C or C++, then GCC is used to compile C code. However I see no intermediate C code on disk, so maybe I'm wrong. However Nim compiler is not as fast as Go compiler.
Comments
Nim has 2 forms of comments. Single line and multiple line. Comment style is inspired from Python. For multi-line comments Nim has chose an original notation: #[...]#. I guess it make sense, it starts with # like the other one.
# Single-line comments start with #
# Multi-line comments start with #[
#[
This is a multi-line comment.
Multi-line comment is not available
in Python. This is original to Nim.
#[ Nested comments are supported! ]#
]#
echo ("hello world")
# Nim do not require function main
# Nim is a free form, language
Discarded """code"""
For ignoring a section of code you can use triple quoted string. This is similar to python except you need the keyword "discard" in front of it. Compiler will evaluate the string and complain that is not used. So you must discard the result of expression.
discard """
# Next line of code is ignored
echo ("print nothing")
"""
Punctuation
Nim do not require ";" at end of every statement but enables multi-line statements without continuation operator. If an expression is not finished, it can continue on next line of code.
# test http://nim-lang.org/docs/strutils.htm;
import strutils as str
echo ("I'm thinking of a number between 41 and 43. Guess which!")
let number: int = 42
var
raw_guess: string
guess: int
while guess != number:
raw_guess = readLine(stdin)
if raw_guess == "": continue # Skip this iteration
guess = str.parseInt(raw_guess)
if guess == 1001:
echo("AAAAAAGGG!")
break
elif guess > number:
echo("Nope. Too high.")
elif guess < number:
echo(guess, " is too low")
else:
echo("Yeeeeeehaw!")
#end of program
Try it:replit.com
Notes
1. In previous example you can see regions of code that are started and never closed. Also sections of code can be nested. My advice: Do not make indentation too deep.
2. Nim do not need round parenthesis for conditionals like JavaScript and Java but is using ":" to finish the condition and start the block of code or section.
3. Symbol ":" is a little bit overused because is also present in variable declarations but not after the keyword var: as you would expect but after each variable. So ":" do not always represent a region or section or block of code.
Declarations
You notice in example above, for declarations you can use lowercase letters to declare the variables. Nim support long variable names that start with a letter and can contain numbers, letters and underscore but no spaces. Underscore is ignored by the compiler.
Declarations can include data type after ":" or not. This is nice because in Java you need to start with data type and that makes data types mandatory. Java has fixed this issue adding a fake data types "var" and "void" which are awkward.
Case convention
Nim is case insensitive with exception of first character, which is case-sensitive. This convention is specific to Nim. Having in mind underscore is ignored then: helloWorld and hello_world would be the same name for Nim. Most of the time compiler will tell you if you make mistakes but not allways.
Special characters
Names can also include numbers and other UTF-8 characters. Sometimes this is nice to improve readability of expressions. For example you can use Greek symbols for variable names combined with numbers and subscript.
Variables
Nim is a statically typed programming language, meaning that the type of an assignment needs to be declared before using the value. Variables can be declared and initialized anywhere in the program. This is very different than Fortran for example where you can define variables only at the beginning of a new block/scope.
var <name> : <type>
var <name> : <type> = <value>
Variables can be defined in group. The type of variables is not mandatory. If you do not specify the type, a default type is used. Nim has type inference.
var
c = -11; # integer
d = "Hello"; # string
e = '!'; # character
Constants
You can define constants using "const" or "let" keywords. In practice you will use mostly "let". It enable you to create variables with initial value or uninitialized and initialize the variable later using an expression. After initial value is set you can not change that value ever again.
# declare 2 variables
let v = 10;
let x = v * 2;
Note: Declaring constant take advantage of type inference. If this is not possible you can specify the data type. This can happen if you have no clue about the initial value.
Messages
Console output is automatic, if an error is signaled. Custom messages can be done using "echo" like in Bash. I guess if you know Bash this is familiar to you but most languages are using keyword "print" or "format" or "write" to make an output.
Error message:In next example we try to print x but an error is present so "echo x" is not executed. Nim is sending error message instead.
var x = 10 / 0
echo x
Output
Warning: integer division by zero [DivByZero] Error: execution of an external program failed: 'echo' '-e' 'nan' [OSError]
Echo messages
Usual penthod to output message at the console:
echo "Hello, world!"
echo 42
echo 3.14
echo 'c'
Output
Hello, world! 42 3.14 c