How to use default generic types in Nim?

Viewed 485

UPDATE: Nim doesn't have defaults for generic types (see the answer).


Why Nim doesn't use default value for generic type?

I would like to have ability to have different Company versions, but I don't want to specify the generic type parameter Company[void]() when I don't need it and just use Company().

But it doesn't work that way, code below won't compile, why? And what's the point of default values for generic type then?

type Company*[T = void] = object
  name*: string
  data*: T

echo Company()
2 Answers

The code doesn't compile because Nim doesn't have default values for generic types AFAIK, not sure where you got the idea that it does (if you find it somewhere in the documentation please link it, I haven't seen this before).

What you can do is alias your default type like this:

type
  Company*[T] = object
    name*: string
    data*: T
  VoidCompany = Company[void]

echo VoidCompany()

Nim is a statically typed language, this means that at some point it needs to figure out what the type of your parameter is. You can do it at compile time or delay it at runtime, but this won't change the fact that the compiler needs to know the type of everything to work properly, the default parameter only determines its value and not the type

Related