I'm hobby programmer and just started playing around with Nim and so far I'm very happy with it. Unfortunately I got stuck on a problem and can't seem to solve it. I want to add a subrange field to an object with the following code:
type
Keypad = ref object
position: range[1..9]
method new(this: type Keypad):Keypad =
result = Keypad()
result.position = 5
var keypad = Keypad.new()
When I run it the compiler complains about "Error: field not initialized: position". I tried changing to position: range[1..9]=5 but then I got "Error: initialization not allowed here" instead.
What is the recommended way to solve this?
(also, is this way of faking a constructor a good solution?)
Hi,
Personally, I would write your code as follows:
type
Keypad = ref object
position: range[1..9]
proc newKeypad(): Keypad =
result = Keypad(position: 5)
let keypad = newKeypad()
Note that method isdynamically dispatched, whilst proc isstatically dispatched. Methods can't be removed with dead code elimination, so proc is usually preferred. The convention newX is also used throughout the standard library.
Also note that object initialization uses the colon (:) to specify the value of a field.