Error:cannot construct 'Array' from 'ListLiteral[Int, Int, Int, Int, Int]' value in 'var' initialize
I'm trying to create a Array[T: AnyType, N: Int] struct but encountered this error when trying to run it:
Please help.
27 Replies
I think you want to change that last
Array([1, 2, 3, 4, 5])
to Array[Int, 5]([1, 2, 3, 4, 5])
, and change fn main():
to fn main() raises:
, since your __init__
can raise. Or you can wrap that initialization inside of main in a try block
now i tried this
i get a mad error
You can also omit the constructor and write
It's a bit easier to both type and read
Wait, this is quite different.
this works but...
this doesn't raise a compile time error lol
You'd probably want to change
[1, 2, 3, 4]
to [1, 2, 3, 4, 5]
So it actually has 5 elementsLOL sir you are very confused
it is done on purpose with 4 elements, I want it to give me a compile time error
huh
Using
constrained
You have to fill up the array with default values then.
Hi sir, can you elaborate?
See the array implementation that some of the devs and I made: https://discord.com/channels/1087530497313357884/1146821935112667288/1148339799808299038
Custom types are necessary until traits get implemented.
Sorry about that. I don't think you can in this case, fetching the length of that ListLiteral isn't done at compile time in this case
Guess you made sense 🙂
Congrats @JIMC, you just advanced to level 1!
That's your impl? Cool
That’s what me and the devs arrived at, yes. I believe it should accomplish the behavior you’re looking for.
I don't think it does, because I want a compile time check e.g. var my_array: Array[Int, 5] = [1, 2, 3] will have a compile time error
that's what i want
And I don't think you can pass it as a parameter either, because trying to do something like
fn __init__[*Ts: AnyType, iterable: ListLiteral[Ts]](inout self) raises:
has a parameter pack plus normal parameters, and the error states keyword args aren't supported yetYou could modify it to receive compile time values.
How do you do try, except in Mojo?
try
except
finally
it works the same way as in python but you raise Error not exceptionyeah but you cannot capture the error message right?
@Three chickens in the green bag Anyway, array is not growable so i think your impl is a vector
and usually a compile time construct
Yes, it is a DynamicVector.
Looks like its difficult to do compile time checking of array length lol, even though obviously at compile time the array is defined as [1, 2, 3, 4, 5, 7] with length of 6.