Skip to content

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.

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 module

Read 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.

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.

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.

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.0
3 items

Going 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.6666666666666665

Without 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.

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:

3

Int(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.

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: 36

You don’t need this for print(t"..."), which takes the t-string directly. See Mojo String Formatting.

  • Mixing Int and Float64 variables. Assigning is this error; doing math like price * qty with an Int and a Float64 gives the related value passed to ‘rhs’ cannot be converted. The fix is the same: Float64(qty).
  • A return statement. The function says -> String but returns a number. Return String(n), or change the return type.
  • Sized integers. Int64 to Int, UInt8 to Int and so on all need Int(...), even though they’re all whole numbers.

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.5

Dividing 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).
  • Optional needs .or_else(...) or .value(); PythonObject needs Int(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

1. With var n = 5, which line builds?
2. Why does var x: Float64 = 4 build, but var x: Float64 = n (with var n = 4) does not?
3. A Python call gives you a PythonObject. How do you get a Mojo Int from it?