Using structs that inherit from a specific trait as a type?

If you have a trait and a struct that inherits from it, could you use that trait's children as a type in, for example, a list? E.g.:
trait MyTrait:
fn __init__(inout self): ...

struct MyStruct(MyTrait):
fn __init__(inout self): pass

fn main():
let my_list = List[structs that inherit from MyTrait](MyStruct())
trait MyTrait:
fn __init__(inout self): ...

struct MyStruct(MyTrait):
fn __init__(inout self): pass

fn main():
let my_list = List[structs that inherit from MyTrait](MyStruct())
7 Replies
sb
sb3mo ago
What happens when you try it?
banananas
banananasOP3mo ago
If i just put the name of the trait i get this:
No description
sb
sb3mo ago
This would depend on dyn/virtual or something in order to work, you might be able to do something with Object? But it wouldn't be as ergonomic as you'd hope I don't want to say without evidence that that feature isn't in yet, but I think that's still waiting (getting that to work pretty much requires either vtables or some global transformation on top of sum types, neither of which Mojo has yet)
banananas
banananasOP3mo ago
Ok... i'll see what i can do with that
sb
sb3mo ago
yeah, sorry, I know that feature is pretty significant hole at the moment
banananas
banananasOP3mo ago
Yeah it is :/
alias AnyList = List[object]

trait Component:
fn __init__(inout self): ...
fn update(inout self): ...
fn render(inout self): ...

@value
struct BaseComponent(Component):
fn __init__(inout self): pass
fn update(inout self): pass
fn render(inout self): pass

struct Entity:
var components: AnyList

fn __init__(inout self, borrowed components: AnyList):
self.components = components

fn update(inout self) raises:
for i in range(self.components.__len__()):
self.components[i].update()

fn render(inout self) raises:
for i in range(self.components.__len__()):
self.components[i].render()

fn addCpt(inout self, value: object):
self.components.append(value)
alias AnyList = List[object]

trait Component:
fn __init__(inout self): ...
fn update(inout self): ...
fn render(inout self): ...

@value
struct BaseComponent(Component):
fn __init__(inout self): pass
fn update(inout self): pass
fn render(inout self): pass

struct Entity:
var components: AnyList

fn __init__(inout self, borrowed components: AnyList):
self.components = components

fn update(inout self) raises:
for i in range(self.components.__len__()):
self.components[i].update()

fn render(inout self) raises:
for i in range(self.components.__len__()):
self.components[i].render()

fn addCpt(inout self, value: object):
self.components.append(value)
i ended up trying smth with object but it throws an error when i try this:
var thing = ecs.Entity(ecs.AnyList(ecs.BaseComponent()))
thing.addCpt(ecs.BaseComponent())
var thing = ecs.Entity(ecs.AnyList(ecs.BaseComponent()))
thing.addCpt(ecs.BaseComponent())
Ethan
Ethan3mo ago
Trait object is not available yet.
Want results from more Discord servers?
Add your server