I'm not sure this can be called polymorphism, but whatever. I'm trying to have an "object" that can be of several types with divergent properties, and so I'm using unions, as they seem the right tool for the job.
But I'm used to OOP, so my understanding of this paradigm is still weak, so I'd like it if someone could look at my code and tell me if it looks ok, and what could be improved.
I'm also getting a crash when I raise the values of W and H too much, and I can't figure out why. I was having this exact problem in my real project and I reproduced it here.
Here's my full test code:
package polym
import "core:fmt"
print := fmt.println
W, H :: 2, 2 // 320, 200 // crashes when using high values
Foo :: struct {
name:string,
f:f32,
l:[2][W][H]int
}
Bar :: struct {
name:string,
i:int,
l:[2][W][H]int
}
Thing :: union {Foo, Bar}
init_foo :: proc() -> Foo {
return Foo {name="foo", f=1}
}
init_bar :: proc() -> Bar {
return Bar {name="bar", i=2}
}
init_thing :: proc(which:string) -> Thing {
switch which {
case "foo": return init_foo()
case: return init_bar()
}
}
use_foo :: proc(t:Thing) {
print(t.(Foo).name)
}
use_bar :: proc(t:Thing) {
print(t.(Bar).name)
}
use_thing :: proc(t:Thing) {
switch v in t {
case Foo: use_foo(t)
case Bar: use_bar(t)
}
}
main :: proc() {
foo := init_thing("foo")
bar := init_thing("bar")
use_thing(foo)
use_thing(bar)
}