Mojo Dict: Store struct instances based on a common trait as CollectionElement.
I'm trying to use a Mojo Dict to store different instances of structs which conform to a common trait. I've created a 'playground' file to work out a solution, but I am stumped. Feels like I'm really close, but no joy yet. Any suggestions?
GitHub: https://github.com/johnsoez4/dict
The code snippet below uses the structs defined earlier in the file. The last line below causes the error:
GitHub
GitHub - johnsoez4/dict
Contribute to johnsoez4/dict development by creating an account on GitHub.
7 Replies
Mark Pet as conforming to CollectionElement. Like this:
If it is a simple struct that is not allocating or owning any pointers then mark it with
@value
decorator. That will ensure it has the functions necessary to be moved and copied the way Collections expect.Thanks for the suggestion Michael!
The code below is the Pet struct from my 'playground' example. As you can see, it already matched your suggestion, but Mojo flags it with the error described in my initial post. I just added the @ value with no discernible effect.
Here's a link to my 'playground' file with all the code.
GitHub: https://github.com/johnsoez4/dict
GitHub
GitHub - johnsoez4/dict
Contribute to johnsoez4/dict development by creating an account on GitHub.
I just made one more change in the main function to use 'CollectionElement' instead of 'Pet' to define the dictionary (see below). The VS Code IDE is happy with this change, but the compiler throws this error:
Alternate
var d = DictStringKey, CollectionElement # Compiler crashes
You need to provide the complete type as a parameter to Dict. Pet requires a parameter T and without that being specificed it is not concrete type that can be passed to Dict. so like this:
Also I think Dict now works witht a plain String. No need to use StringKey.
This only works for MyPet (i.e. cats), but not for YourPet (i.e. dogs). Both MyPet and YourPet structs use the trait TPet defined previously in the file.
So I'm trying to assign the Dict with TPet instead of MyPet:
var d = Dict[StringKey, Pet[TPet]]() # Error here
But get this error:
I just removed StringKey and synced the latest to GitHub. Only works for MyPet, not YourPet.I don't think you can use a trait as the parameter when you need to make a concrete type. You need to pass an actual fully known type to Dict. using
Pet[YourPet]
works for me. If you want a Dict that holds a Pet with T either MyPet or YourPet, I think you would need to use a Variant[MyPet, YourPet]. I am not sure how well that will work but that is how you allow for two possible concrete types.I was hoping for a different answer...this seemed like an elegant solution. 😀
I'd like to store any type that adheres to the trait, even ones that haven't been written yet. I'll play with the Variant and see how it goes.
Thanks Michael!