The playground
The code below won't compile because the func init uses the let time_d_format variable from the outer scope.
import strutils, strformat, times
type TimeD* = object
year*: Natural
month*: 1..12
day*: 1..31
let time_d_format = times.init_time_format "yyyy-MM-dd"
func init*(_: typedesc[TimeD], time: string): TimeD =
let t = times.parse(time, time_d_format, times.utc())
TimeD(year: t.year, month: t.month.ord, day: t.monthday)
echo TimeD.init("2020-01-01")
The type of the time_d_format variable is an object, so it seems like as soon as I declared it as immutable with let time_d_format - it should allow to use it in the func init. I.e. it's ok to use immutable data in pure functions, no?
What would be the proper way to implement that? My thought for using shared variable time_d_format is to optimize performance - compute it once and share between all the func init.
type TimeFormat* = object
patterns: seq[byte]
formatStr: string
Seems like it has nothing to do with using let global variable, since https://nim-lang.org/docs/times.html#utc utc is not noSideEffect proc.
Though using let variables is a sideeffect still. If you need to have some kind of global value and no side effects when reading it you should use const