List literals in Mojo
Square brackets build a List, and the element type follows.
def main():
var primes = [2, 3, 5, 7, 11]
var ratios = [0.5, 1.5, 2.5]
# Type a String list explicitly; bare literals infer StringSlice.
var names: List[String] = ["ada", "grace", "alan"]
print(len(primes), primes[0], primes[len(primes) - 1])
print(ratios[1])
for name in names:
print(name)
How it works
[2, 3, 5, 7, 11]infersList[Int]from its contents.- String lists need the explicit
List[String]annotation. - There is no negative indexing, so the last item is
xs[len(xs) - 1].
Keywords and builtins used here
ListStringdefforlenmainprintvar
The run, in numbers
- Lines
- 9
- Characters to type
- 290
- Tokens
- 83
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 59 seconds.
Step 1 of 6 in Collections, step 12 of 26 in Language basics.