I don’t know how to write titles
Hey! I recently started writing a little mini-project to get a feel for what Odin is like. At this point, it’s not really interactive, but it might be in the future. I’ve stumbled into an issue of how to design the way the structs are laid out.
What I’m doing is I have a struct like Widget
, and then structs like Label
or Button
which do a using widget: Widget
in their definitions. I then have a repr
proc (short for ‘representation’) which is meant to take in a widget and return a string representation of it.
The issue is that this using
call doesn’t work like inheritance as I’m used to. For example, when I have a ^Widget
, but the object that contains the widget is actually a ^Button
, I can’t use the fields of the button like I’m used to.
I don’t know how to explain my problem. Maybe it would work better if I just showed an example of what I have:
My structs:
Widget :: struct {
id: string,
contents: [dynamic]^Widget,
}
Box :: struct {
using widget: Widget,
orient: Orient,
}
Button :: struct {
using widget: Widget,
text: string,
}
Label :: struct {
using widget: Widget,
text: string,
}
Definition of repr
procs:
repr :: proc{
repr_box,
repr_button,
repr_label,
}
repr_box :: proc(box: ^Box) -> string {
arr := make([dynamic]string)
for widget, _ in box.contents {
// ISSUE: box.contents is a [dynamic]^Widget, but i want to "upcast" (???)
// it to its 'real' type so that the repr(widget) call works properly
append(&arr, strings.concatenate({" ", repr(widget), "\n"}))
}
output := strings.concatenate({"<box>:\n", strings.concatenate(arr[:])})
return output
}
repr_button :: proc(box: ^Button) -> string {
return strings.concatenate({"<button \"", box.text, "\">"})
}
repr_label :: proc(box: ^Label) -> string {
return strings.concatenate({"<label \"", box.text, "\">"})
}
Again, this project is just at a beginning stage, so some things might be very obviously bad design. All I want right now is for the basic repr
implementation to work.
Is there a way to make this work as it is? Am I going in the completely wrong direction, and there’s a much more idiomatic Odin solution here? I don’t know. Again, I can’t stress this enough, this is my first project ever in Odin, so there might be some feature that does this exactly as I want that I’m missing entirely.
Thanks in advance!