Skip to content

User defined default values #233

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
pmetras opened this issue Jun 12, 2020 · 4 comments · Fixed by nim-lang/Nim#20480
Closed

User defined default values #233

pmetras opened this issue Jun 12, 2020 · 4 comments · Fixed by nim-lang/Nim#20480

Comments

@pmetras
Copy link

pmetras commented Jun 12, 2020

User manual defines how variables are initialized. In fact, memory used by the variables is 0-filled.

Proposal

The special func default(t: typedesc[T]): T can be defined by the user to specify a different default value. When it exists, the compiler will call this proc to initialize variables of type T. In such case, 0-filled memory does not occur and it's replaced by default calls.

Justification

  • Let the user select the default value. The following program won't display error message Warning: Cannot prove that 'f' is initialized. This will become a compile time error in the future. [ProveInit]
type
  Val = range['A' .. 'Z']

func default(a: typedesc[Val]): Val =
  'A'

proc foo =
  var f: Val
  echo "f = '", f, "', ord = ",  ord(f)

foo()
  • Better control over default values for ranges, enum, tuples, arrays, etc.
  • No change to existing behaviour and limited change to documentation.
  • Some [ProveInit] warnings can be corrected by users.
@dom96
Copy link
Contributor

dom96 commented Jun 13, 2020

I like this idea, since AFAIK the compiler already has a concept of default.

@simonkrauter
Copy link

Maybe related to:

@snej
Copy link

snej commented Jun 27, 2020

Great feature, but the syntax seems overly complex to me for something whose effect is so simple. How about proc =init(var T), since it’s functionally the opposite of the =destroy function? (insert your own backticks around the name; I can’t figure out how to escape them in Markdown.)

@iacore
Copy link

iacore commented Oct 19, 2021

It should probably be =init.

On another though maybe using default(T) explicitly is better.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
5 participants