--- layout: page title: Examples ---

Examples

Nim is simple, yet fast

Nim was designed from the ground up to be simple, yet powerful. Forget about pointers and manual memory management*, Nim's threaded garbage collector will automatically ensure that your code keeps its memory footprint low. Even though it has the benefits of an interpreted language, as a compiled language, Nim can achieve very high performance when optimized, on par with C or C++.

* Can still be done manually if needed.


# Compute average line length
var
  sum = 0
  count = 0

for line in stdin.lines:
  sum += line.len
  count += 1

echo("Average line length: ",
  if count > 0: sum / count else: 0)
      


# Create and greet someone
type Person = object
  name: string
  age: int

proc greet(p: Person) =
  echo "Hi, I'm ", p.name, "."
  echo "I am ", p.age, " years old."

let p = Person(name:"Jon", age:18)
p.greet() # Or greet(p)
      

Nim is type safe

With its automatic array bounds checking, among many other safety features, Nim is one of the safest languages to program in.


Nim plays well with others

Nim is interoperable with C and C++, which means you can not only call C or C++ code if needed, but also leverage the power of existing libraries such as GTK+, libui, SDL, SFML and many more.


# Declare a C procedure…
proc unsafeScanf(f: File, s: cstring)
  {.varargs,
    importc: "fscanf",
    header: "<stdio.h>".}

# …and use it…
var x: cint
stdin.unsafeScanf("%d", addr x)
      


# A simple html server
import
  jester, asyncdispatch, htmlgen

routes:
  get "/":
    resp h1("Hello world")

runForever()
      

Nim for Web developers

Using the Sinatra-like Jester Web framework, Nim makes it easy to quickly create Web applications.

Ready to discover Nim?

Download