Nim is a statically typed programming language. Any variable must be declared before use and assigned a value.
It provides three keywords for NIM variables
- var - create mutable variables
- let - create immutable variables
- const - constants and fixed values
How to declare a variable in Nim
a variable declared using the below syntax
var variable: datatype or var variable: datatype = value
var is a keyword
variable is a valid identifier
datatype is an inbuilt type provided by the language.
var number: int var number: int=123
Nim provides Type Inference, You can declare the variable type by assigning the value
Here number type is inferred from the value assigned. value is of int type.
How to declare multiple variables
There are two syntax ways of declaring multiple variables.
one way using a comma separator
var a,b: int
variables a and b are declared of type int. With this, You can declare multiple variables of the same type only.
Another way to use multiple variables with different types
var a,b: int str1,str2: string
Variables are declared with indentation with two spaces on each line with the same type
variable scopes allow using the variable based on the place where the variable is declared.
There are two types of variable scopes.
- Local Scope: Variables declared in a functional or block scopes
- Global Scope: Variables declared globally
nim var variable
Variables declared with var are values can be changed at any time, but the type can not be changed
Valid var declarations
var str = "one" str = "two"
var str = "one" str = 1 # Error
nim let variable
let is another way to declare a variable similar to the
Let allows you to declare a single variable. and once the variable is declare, not able to assign the value, but you can assign compile time expressions
In the below, the str variable is declared assigned with one at compile time. if you assign with a new value, It throws an error
let str = "one" str = "two" # Error
let allows you to assign expression,
const does not allow constant expression value
let str = compile time expressions valie const str =expression # Error
Nim Constant variables
const keyword allows you to declare a value with an assigned value once. and variable is immutable which means, its value can not be changed once declared.
const n = 12 n = 20 # error
variables are assigned and evaluated at compile time and their value never changed at runtime.
Variable default values
Variables declared in Nim has default value based on datatype if there is no assigned value.
|String||Empty space ("")|
|tuple[v1: type1, v2: type2, …]||(Default(type1),Default(type2))|