Mojo Error: cannot implicitly convert 'X' value to 'Y'
error: cannot implicitly convert 'X' value to 'Y' means you put a value of type X somewhere that needs a Y, and Mojo won’t change it for you. The most common versions are 'Int' value to 'Float64', 'Int' value to 'String' and 'PythonObject' value to 'Int'. The fix is to convert the value yourself, so it’s clear in the code that a conversion happens. For the other errors in this series, see Mojo Errors Explained.
The error message
Section titled “The error message”def main(): var count = 8 var average: Float64 = count print(average)average.mojo:3:28: error: cannot implicitly convert 'Int' value to 'Float64' var average: Float64 = count ^~~~~mojo: error: failed to parse the provided Mojo source moduleRead the two types in the message as “from” and “to”: the value on the right (count) is an Int, and the place it’s going (average) is a Float64. The ^~~~~ marks point at the value that has the wrong type.
What it means
Section titled “What it means”Every variable, argument and return value in Mojo has one fixed type. When you assign, pass or return a value, its type has to match. An implicit conversion is one that happens silently, without you writing anything. Mojo allows only a few of those, mostly for literals: var x: Float64 = 4 is fine, because the literal 4 can become any number type. A variable of type Int can’t become a Float64 silently.
You’ll see this message in a few places, and the end of the message sometimes tells you where:
| You wrote | Message |
|---|---|
var average: Float64 = count |
cannot implicitly convert 'Int' value to 'Float64' |
return n in a function -> String |
cannot implicitly convert 'Int' value to 'String' |
count = "nine" when count is an Int |
cannot implicitly convert 'StringLiteral["nine"]' value to 'Int' |
var r: Int = math.floor(3.7) with Python’s math |
cannot implicitly convert 'PythonObject' value to 'Int' |
var n: Int = maybe where maybe is Optional[Int] |
cannot implicitly convert 'Optional[Int]' value to 'Int' |
StringLiteral["nine"] is the type of the text literal "nine". Mojo shows the literal’s value inside the brackets.
Why Mojo does this
Section titled “Why Mojo does this”Conversions can lose information or cost time. Int to Float64 can round very large numbers, Float64 to Int drops the decimals, and Int64 to Int32 can overflow. Python hides these steps; Mojo wants you to see them. The types and literals cheat sheet puts it plainly: number conversions are explicit.
How to fix it
Section titled “How to fix it”Fix 1: Convert with the type’s name
Section titled “Fix 1: Convert with the type’s name”This is the fix most of the time. Call the target type like a function: Float64(...), String(...), Int(...), Int32(...):
def label(n: Int) -> String: return String(n) + " items"
def main(): var count = 8 var average: Float64 = Float64(count) print(average) print(label(3))Output:
8.03 itemsGoing from Float64 to Int works the same way, with Int(x), and drops the part after the point. One thing that can’t be converted like this is text: Int("42") reads a number from a string, and since that can fail, it needs try or raises (see cannot call function that may raise). The Mojo Type Conversion lesson has all the common conversions in one place.
Fix 2: Make the types match from the start
Section titled “Fix 2: Make the types match from the start”Sometimes the annotation is the mistake, not the value. If average should hold the result of a division, do the math in Float64 and let Mojo work out the type:
def main(): var count = 8 var average = Float64(count) / 3 print(average)Output:
2.6666666666666665Without the : Float64, average simply takes the type of the expression. And if a variable needs to hold text and a number at different times, it really should be two variables, like count and count_text. A Mojo variable keeps the type it was created with.
Fix 3: Unwrap an Optional
Section titled “Fix 3: Unwrap an Optional”An Optional[Int] might hold an Int or nothing, so it can’t stand in for an Int. Take the value out, with a fallback for “nothing”:
def main(): var maybe: Optional[Int] = 5 var n: Int = maybe.or_else(0) print(n)Output:
5.or_else(0) gives the value, or 0 if there’s none. .value() also works, but only use it when you’ve checked first with if maybe:. See Mojo Optional.
Fix 4: Convert a PythonObject back to Mojo
Section titled “Fix 4: Convert a PythonObject back to Mojo”Everything that comes back from Python is a PythonObject. To get a Mojo Int, Float64 or String, convert it with the py= keyword:
from std.python import Python
def main() raises: var math = Python.import_module("math") var r = Int(py=math.floor(3.7)) print(r)Output:
3Int(py=...), Float64(py=...) and String(py=...) all work this way. The Python types page of the Mojo manual and our Mojo Python Types lesson cover the details.
Fix 5: Turn a t-string into a String
Section titled “Fix 5: Turn a t-string into a String”A t-string (t"...") is its own type, not a String, so var msg: String = t"Age: {age}" fails with a long message about 'TString[...]'. Wrap it in String(...):
def main(): var age = 36 var msg = String(t"Age: {age}") print(msg)Output:
Age: 36You don’t need this for print(t"..."), which takes the t-string directly. See Mojo String Formatting.
Where you’ll usually see it
Section titled “Where you’ll usually see it”- Mixing
IntandFloat64variables. Assigning is this error; doing math likeprice * qtywith anIntand aFloat64gives the related value passed to ‘rhs’ cannot be converted. The fix is the same:Float64(qty). - A return statement. The function says
-> Stringbut returns a number. ReturnString(n), or change the return type. - Sized integers.
Int64toInt,UInt8toIntand so on all needInt(...), even though they’re all whole numbers.
Related errors
Section titled “Related errors”- invalid call: value passed to ‘x’ cannot be converted from ‘A’ to ‘B’: the same problem, but in a function argument or an operator.
- the SIMD type must be floating point: what you get when a float literal like
3.7goes where anIntis needed. - cannot call function that may raise: what
Int("42")gives in a function withoutraises. - All Mojo error pages: the full list.
Practice
Section titled “Practice”1. Average of a list
Section titled “1. Average of a list”This program should print the average of the scores, 7.5. Fix the conversion error.
def main(): var scores: List[Int] = [6, 9, 7, 8] var total = 0 for s in scores: total += s var average: Float64 = total / len(scores) print(average)Hint: total / len(scores) is Int / Int, which is an Int in Mojo. Convert both sides to Float64 before dividing.
Show solution
def main(): var scores: List[Int] = [6, 9, 7, 8] var total = 0 for s in scores: total += s var average: Float64 = Float64(total) / Float64(len(scores)) print(average)Output:
7.5Dividing two Int values gives an Int (here 7, the decimals are dropped), which can’t go into a Float64. Converting both sides first makes the division happen in Float64, and the result fits.
- The message names two types: the value’s type from, and the type it needs to be.
- Mojo only converts literals silently. Variables need an explicit conversion.
- Convert with the type’s name:
Float64(n),String(n),Int(x). Optionalneeds.or_else(...)or.value();PythonObjectneedsInt(py=...)and friends.- If the annotation is wrong, fix the annotation or leave it out and let Mojo infer the type.
Next up: value passed to ‘x’ cannot be converted from ‘A’ to ‘B’, the same idea for function arguments.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Types and literals cheat sheet: which conversions are explicit, and how literals become types.
- Types in the Mojo manual: the built-in number, string and collection types.
- Python types in the Mojo manual: converting between
PythonObjectand Mojo types. - Mojo Type Conversion: our lesson with all the everyday conversions.