nim-lang / RFCs

A repository for your Nim proposals.
135 stars 26 forks source link

`=default` type bound operator to override `default` and `var` initialization #290

Open timotheecour opened 3 years ago

timotheecour commented 3 years ago

https://github.com/nim-lang/RFCs/issues/252 was already accepted in the form of https://github.com/nim-lang/RFCs/issues/252#issuecomment-705113779

This leaves open another point, which is initialization for non-object types (as was suggested in https://github.com/nim-lang/RFCs/issues/252#issuecomment-718236794)

proposal

allow type bound =default operator to override default and var initialization. it must be a compileTime proc (or at least compiler will only call it at CT).

invariant: var a: T is always equivalent to var a = T.default

example 1

# sub.nim:
type Bar* = distinct bool
proc `=default`(t: typedesc[Bar]): Bar {.compileTime.} = true.Bar
  # type bound operator, so doesn't need to be exported

# main.nim
import sub
var a1 = Bar.default
doAssert a1.bool
var a2: Bar
doAssert a2.bool

example 2

in system.nim, add

proc `=default`(t: typedesc[range]): t = t.low

so that:

var a: range[10..20]
static: doAssert a == 10
cooldome commented 3 years ago

Why not =init(x: var T) as proposed in #252?. It is more efficient, no extra move/copy operation required

timotheecour commented 3 years ago

why would it be more efficient? =default is {.compileTime.} and affect semantics of var initializaiton, so that:

var a: Bar
  # a is not zero-initialized, it's directly initialized to `=default(Bar)`,
  # possibly from ROM
github-actions[bot] commented 7 months ago

This RFC is stale because it has been open for 1095 days with no activity. Contribute a fix or comment on the issue, or it will be closed in 30 days.