Trying out Nim

Even though it has little adoptation, Nim looks like a cool promissing language! Lets try it out.

Getting started is easy, using choosenim

curl https://nim-lang.org/choosenim/init.sh -sSf | sh

After answering a few questions, you have Nim installed and can call

nim -v

Hello World

Nim’s package manager is called Nimble. Lets use it:

nimble init helloworld

Select “Binary” as “package type”.

Nimble will now create a new folder called helloworld. The folder contains a file called helloworld.nimble which describes the new projects dependencies.

A simple hello world program is places in src/hello.nim it looks like this:

# This is just an example to get you started. A typical binary package
# uses this file as the main entry point of the application.
when isMainModule:
   echo("Hello, World!")

Like Python, Nim use whitespace (spaces, not tabs) indentation to indicate scoope. No {} is used.

To compile the program, write:

nim c src/hello.nim

or, to compile and run:

nim c -r src/hello.nim

or for projects, you ban use Nimble to build the project:

nimble build

To view the c source of your Nim program, try:

mkdir cache
nim c --nimcache=cache src/hello.nim

Now you can find the c source in the cache folder.

A bit more hello world.

helloworld.nim

import std/strutils

proc main() =
  let s = "Hello, World!"
  for c in s: # iterate chars in string
    if c=='o': # replace o with 0
      stdout.write "0"
    else:
      stdout.write c
  stdout.write "\n"
  stdout.flushFile()

when isMainModule:
  main()