typestar

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

  1. Int(text) parses a String, which is why main is marked raises.
  2. Float64(count) widens an Int so the division stays fractional.
  3. String(count) goes the other way, ready for concatenation.

Keywords and builtins used here

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.

Type this snippet

Step 5 of 6 in Variables & functions, step 5 of 26 in Language basics.

← Previous Next →

Converting between types in other languages