Hi, this is probably a stupid newb question, but I don't understand how to implement control flow by checking types. The following code is what I have:
import typetraits
type Foo = object
foos: string
type Bar = object
bars: string
let foo = Foo( foos: "I'm a Foo" )
let bar = Bar( bars: "I'm a Bar" )
proc tell_type( thing:Foo|Bar ) =
if thing.type is Foo:
echo thing.foos
elif thing.type is Bar:
echo thing.bars
tell_type(foo)
Which gives the error:
Error: undeclared field: 'bars' for type types.Foo
I think I understand the problem: the compiler doesn't care that I've got if/else statements, it doesn't know that "thing.bars" has to be a "Bar" when I call it. My questions are these, why isn't this okay, and what should I be doing instead?
Or am I trying to do something stupid?
tell_type is an implicit generic procedure due to the Foo|Bar. That means for each encountered type for which it is used, a procedure taking that type will be generated.
Now, if is a runtime construct. So when you say if ... is T it's checking at runtime whether something is T. What you want to tell the compiler of course is to do this at compile time. That's what when is for. It's the compile time version of if essentially.
Just replace if by when and it should work.