I have the following type declarations:
import tables
type
A = object
i: int
ATableRef = TableRef[string, A]
where ATableRef is kind of a slightly higher-level shortcut for a specific``TableRef``. I'm using ATableRef as parameter type in procs to avoid repeating the individual types.
Now I want to create a new ATableRef. This works:
var newTable = newTable[string, A]()
but has the disadvantage that it repeats the types I used in the definition of ATableRef.
I tried the "seemingly obvious"
var newTable: ATableRef = newTable()
hoping that the compiler would be able to infer the type, but the compiler tells me:
/usercode/in.nim(16, 35) template/generic instantiation of `newTable` from here
/playground/nim/lib/pure/collections/tables.nim(784, 16) Error: cannot instantiate: 'A'
How can I create an object of ATableRef without repeating the types string and A?
The above code is combined here for experimenting: https://play.nim-lang.org/#ix=2tqq .
I guess if the original goal isn't achievable with some use of TableRef or newTableRef, probably the cleanest approach is defining a new "constructor":
func newATable(): ATableRef =
newTable[string, A]()
:-) . That would also help if newATable needs more set-up in the future. If you're very strict about it, you could consider this approach a "YAGNI violation", but I think it's fine. ;-)
What's wrong with
var myTable = ATableRef()
It wasn't clear whether this would be enough.
It's in the spec that tables don't need explicit initialization: "Starting from Nim v0.20, tables are initialized by default and it is not necessary to call this function explicitly." That means that plain new works and will always work.
Awesome, now that is useful information.
Unnecessary and poor practice.
The only difference I see between your and my code is the line to create the actual table. And that's different because it wasn't clear whether the second form would be reliable (see the discussion so far).
Thanks anyway! ;-)