As always the Nim Manual is a treasure trove. I just discovered this [move 
optimization](https://nim-lang.org/docs/manual.html#ast-based-overloading-move-optimization)

With the {call} constraint you can have 2 procs, one if there are multiple 
references and one if the compiler knows the reference is unique !
    
    
    proc `[]=`*(t: var Table, key: string, val: string) =
      ## puts a (key, value)-pair into `t`. The semantics of string require
      ## a copy here:
      let idx = findInsertionPosition(key)
      t[idx].key = key
      t[idx].val = val
    
    proc `[]=`*(t: var Table, key: string{call}, val: string{call}) =
      ## puts a (key, value)-pair into `t`. Optimized version that knows that
      ## the strings are unique and thus don't need to be copied:
      let idx = findInsertionPosition(key)
      shallowCopy t[idx].key, key
      shallowCopy t[idx].val, val
    
    var t: Table
    # overloading resolution ensures that the optimized []= is called here:
    t[f()] = g()
    

Reply via email to