Nim: [RFC] update object syntax: obj.updateObj(field1 = foo, field2 = "bar")

Created on 2 Jul 2018  路  5Comments  路  Source: nim-lang/Nim

The following seems quite useful, I wonder whether it's already in stdlib ? If not would that belong in system.nim ?

import macros
import strformat

macro updateObj*(src: typed, n: varargs[untyped]): typed =
  result = newNimNode(nnkStmtList, n)
  for x in n:
    let cmd = fmt"{toStrLit(src)}.{toStrLit(x)}"
    # or: let cmd = $(toStrLit(src)) & "." & $(toStrLit(x))
    result.add(parseStmt(cmd))

# usage:
type Foo=object
  a:string
  b:int
  c:seq[string]
  d:bool

proc test_updateObj*()=
  var opt: Foo
  opt.updateObj(b = 3 - 5, a="asdf", c = @["baz", """ ? """], d=true)
  echo opt
Feature RFC

Most helpful comment

I vote for this to be made put in a Nimble package. If it becomes popular enough we can adopt it into the stdlib later.

All 5 comments

Heads up: toStrLit(x) is just newStrLitNode(repr(x)), $toStrLit(x) is just repr(x).

This macro could be more generalized in a tap or doto macro as in ruby or clojure and that wouldn't really fit in with the stdlib in my opinion, instead some general utility Nimble package.

There is also automatic self insertion that, while not the same thing, may be used in similar cases

I vote for this to be made put in a Nimble package. If it becomes popular enough we can adopt it into the stdlib later.

ok, closing in favor of nimble package

I'm surprised I didn't remember this before, but this is already in the package cascade

Was this page helpful?
0 / 5 - 0 ratings

Related issues

SolitudeSF picture SolitudeSF  路  3Comments

kobi2187 picture kobi2187  路  4Comments

juancarlospaco picture juancarlospaco  路  3Comments

zaxebo1 picture zaxebo1  路  4Comments

zzz125 picture zzz125  路  4Comments