Properties

Nim has no need for get-properties: Ordinary get-procedures that are called with the method call syntax achieve the same. But setting a value is different; for this a special setter syntax is needed:

  1. # Module asocket
  2. type
  3. Socket* = ref object of RootObj
  4. host: int # cannot be accessed from the outside of the module
  5. proc `host=`*(s: var Socket, value: int) {.inline.} =
  6. ## setter of hostAddr.
  7. ## This accesses the 'host' field and is not a recursive call to
  8. ## ``host=`` because the builtin dot access is preferred if it is
  9. ## available:
  10. s.host = value
  11. proc host*(s: Socket): int {.inline.} =
  12. ## getter of hostAddr
  13. ## This accesses the 'host' field and is not a recursive call to
  14. ## ``host`` because the builtin dot access is preferred if it is
  15. ## available:
  16. s.host
  1. # module B
  2. import asocket
  3. var s: Socket
  4. new s
  5. s.host = 34 # same as `host=`(s, 34)

A proc defined as f= (with the trailing \=) is called a setter. A setter can be called explicitly via the common backticks notation:

  1. proc `f=`(x: MyObject; value: string) =
  2. discard
  3. `f=`(myObject, "value")

f= can be called implicitly in the pattern x.f = value if and only if the type of x does not have a field named f or if f is not visible in the current module. These rules ensure that object fields and accessors can have the same name. Within the module x.f is then always interpreted as field access and outside the module it is interpreted as an accessor proc call.