M
Modular4mo ago
toasty

Is it possible to store a list of References in Struct?

Calling all reference experts! I've seen some conversations lightly touching on the topic but I haven't seen anything concrete. I know I can do something like this:
struct CLI[is_mutable: Bool, lifetime: AnyLifetime[is_mutable].type]():
var commands: List[Reference[Command, is_mutable, lifetime]]
struct CLI[is_mutable: Bool, lifetime: AnyLifetime[is_mutable].type]():
var commands: List[Reference[Command, is_mutable, lifetime]]
But I can't actually add any references to the list, the lifetimes won't match. Is this something that's not possible in Mojo's current state?
7 Replies
benny
benny4mo ago
you could try making two lists for both possible mutabilities inside a struct, that should hopefully solve the issue
toasty
toasty4mo ago
Sorry, I’m not following 😅 do you have any examples?
Ryan
Ryan4mo ago
It is possible if the items going into the list share a lifetime. If they are stored together in some other structure you can use that structures lifetime for the list. Or maybe you could use a MutableStaticLifetime for the list. Something like this
var arr = InlineArray[command, 10](command())
var cli = CLI[True, __lifetime_of(arr)]()
# if it had an add method
cli.add(arr[i])
var arr = InlineArray[command, 10](command())
var cli = CLI[True, __lifetime_of(arr)]()
# if it had an add method
cli.add(arr[i])
toasty
toasty4mo ago
Ahh that makes sense. Seems like a list of refs isn’t the approach I want. I was hoping to define and configure Command structs, and add references to them to the CLI struct. But maybe it would be better to transfer ownership of the commands to the CLI struct and add the configuration functions to the CLI struct instead
Ethan
Ethan4mo ago
You probably want to use Arc:
var a = List[Arc[Int]](2,3,4)
var a = List[Arc[Int]](2,3,4)
toasty
toasty4mo ago
@Ethan Thanks for offering some advice! I'm using Arc for the current implementation, it does the job for the most part aside from needing to save arc function args as a variable before it can be dereferenced.
Ethan
Ethan4mo ago
I’m glad it worked for you.
Want results from more Discord servers?
Add your server