Methods in Nim

Nim supports methods defined on custom types.

import std/strformat

type
  Rect = object
    width, height: int

# This `area` method is defined for the `Rect` type.
proc area(r: Rect): int =
  r.width * r.height

# Methods can be defined for either ref or value types.
# Here's an example of a value type method.
proc perim(r: Rect): int =
  2 * r.width + 2 * r.height

proc main() =
  var r = Rect(width: 10, height: 5)

  # Here we call the 2 methods defined for our type.
  echo fmt"area: {r.area()}"
  echo fmt"perim: {r.perim()}"

  # Nim automatically handles conversion between values
  # and refs for method calls. You may want to use
  # a ref type to avoid copying on method calls or
  # to allow the method to mutate the receiving object.
  var rp = new Rect
  rp.width = 10
  rp.height = 5
  echo fmt"area: {rp.area()}"
  echo fmt"perim: {rp.perim()}"

main()

To run the program:

$ nim c -r methods.nim
area: 50
perim: 30
area: 50
perim: 30

Next, we’ll look at Nim’s mechanism for grouping and naming related sets of methods: interfaces (known as concepts in Nim).