Converting between types in Mojo
Mojo converts with constructors rather than casts.
def main() raises:
var text = String("42")
var count = Int(text)
var ratio = Float64(count) / 8.0
print(count, ratio)
print(Int(3.9), Float64(7), Bool(0))
print("count as text: " + String(count))
How it works
Int(text)parses aString, which is whymainis markedraises.Float64(count)widens anIntso the division stays fractional.String(count)goes the other way, ready for concatenation.
Keywords and builtins used here
Float64IntStringdefmainprintvar
The run, in numbers
- Lines
- 7
- Characters to type
- 195
- Tokens
- 60
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 42 seconds.
Step 5 of 6 in Variables & functions, step 5 of 26 in Language basics.