Learning Nim: var vs let vs const

sigmapie8

Manav

Posted on February 12, 2020

Learning Nim: var vs let vs const

I've been exploring Nim-lang these days. Its one of the new languages in town and if you're hearing about it the first time then you should definitely checkout this FAQ.

var, let and const all of them are used to hold value in Nim, but there are slight differences that beginners need to be aware of.

var

var can be used in 3 different forms to define a variable.


# 1. Declare first and assign later.
var <variable-name>: <variable-type>
<variable-name> = <value> 

# 2. Declare and assign at the same time.
var <variable-name>: <variable-type> = <value>

# 3. Directly assign the variable, Nim compiler is smart
#    enough to guess the type of the value
var <variable-name> = <value>

# Following any case, the variable can be reassigned a value
<variable-name> = <value>

Can we change the type of the variable while reassigning?

# No
var x = 9
x = "string" #throws type mismatch error

let

let also works like var, except let requires initialization and once the value is assigned, it cannot be changed.

let <variable-name>: <type> = <value> #works
let <variable-name> = <value> #works

let <variable-name>: <type> #ERROR
<variable-name> = <value> #ERROR

How about the following case?

let x = 9
let x = 10 #throws ERROR. It will be considered as redefinition of x.

const

const keyword is used if we want to assign a constant value to a variable and the value is known while writing the code. Once a value is assigned to it, it cannot be reassigned.

const <variable-name>: <type> = <value> #works
const <variable-name> = <value>

const <vaiable-name>: <type> #ERROR
<variable-name> = <value> #ERROR

But then what's the difference between const and let?

const and let are almost the same except that const expressions are evaluated at compile time and let expressions are evaluated at run time. For example:

var x = 9
let y = x+2 #works
const z = x+2 #throws ERROR

The compiler needs an absolute value for a constant expression that can be bound to the variable at compile time.

If you learnt something, hit ❤️ and share. Others deserve learning too 🙂

💖 💪 🙅 🚩
sigmapie8
Manav

Posted on February 12, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Learning Nim: var vs let vs const
nim Learning Nim: var vs let vs const

February 12, 2020