ModularM
Modular3y ago
1 reply
Xcur

Can i have a list of structs with different parameters?

Lets say I have a struct like the one below, is it possible to have a list of structs that have different values inside their compile time parameters? This is just a sample struct, I know it's trivial and you wouldn't create a Name struct but this is just demonstrate the concept.

trait Proto(Stringable, CollectionElement):
    fn print(self) -> None: ...

struct Name[DataSize: Int](Proto):
    var name: String
    
    fn __init__(inout self, owned name: String) -> None:
        self.name = name^

    fn __moveinit__(inout self, owned existing: Self) -> None:
        self.name = existing.name^
    
    fn __copyinit__(inout self, other: Self) -> None:
        self.name = other.name
    
    fn __str__(self) -> String:
        var result: String = ""
        for i in range(DataSize):
            result += self.name[i]
        return result
    
    fn print(self) -> None:
        print(self)


I could only implement it if I had DataSize as the same for each, but I would like to have a list of different DataSize name structs.

# this worked
var names = DynamicVector[Name[DataSize = 5]]()
# this does not work
var names = DynamicVector[Name]()


Is there a way to abstract it away, by using traits with all the necessary methods and then a wrapper struct that holds a name field with the trait as its type that I put each Name struct into? Then I could put the wrapper struct as a parameter in DynamicVector?
Was this page helpful?