-
-
Notifications
You must be signed in to change notification settings - Fork 9
InitializerList literal
IsaacShelton edited this page Mar 21, 2022
·
1 revision
InitializerList
literals are a list of values surrounded by curly braces and separated by commas:
{1, 2, 3, 4, 5, 6}
{'A'ub, 'B'ub, 'C'ub, 'D'ub, 'E'ub, 'F'ub}
{"Apples", "Bananas", "Oranges", "Grapes", "Peaches"}
InitializerList
literals have the type of <$T> InitializerList
where $T
is the type of the first element:
Example | Result Type |
---|---|
{1, 2, 3, 4, 5, 6} |
<long> InitializerList |
{1us, 2, 3, 4, 5, 6} |
<ushort> InitializerList |
{{1, 2, 3} as <int> Array, {1, 2, 3}, {1, 2, 3}} |
<<int> Array> InitializerList |
In order for InitializerList
values to properly convert to other types, user-defined conversions must be created. In the following example, we provide a user-defined conversion that allows InitializerList
literals to be automatically converted to a custom array type:
import InitializerList
struct <$T> MyArray (items *$T, length usize)
implicit func __as__(list <$T> InitializerList) <$T> MyArray {
my_array POD <$T> MyArray
my_array.items = list.array
my_array.length = list.length
return my_array
}
func main {
values <long> MyArray = {1, 2, 3, 4, 5}
}