Mojo Error: use of uninitialized value 'x'
error: use of uninitialized value 'x' means you read a variable at a point where it might not hold a value. That happens in two very different situations: the variable never got a value on some path through your code, or it had one and gave it away with ^. Mojo uses the same message for both, so the first job is to work out which one you have. For the other errors in this series, see Mojo Errors Explained.
The error message
Section titled “The error message”def main(): var temp = 31 var advice: String if temp > 30: advice = "Stay inside" elif temp < 5: advice = "Wear a coat" print(advice)weather.mojo:8:10: error: use of uninitialized value 'advice' print(advice) ^weather.mojo:3:9: note: 'advice' declared here var advice: String ^mojo: error: failed to run the pass managerTwo places are marked: where the variable is used (line 8) and where it was declared (line 3). The problem is somewhere on the way between them. Here, if temp is between 5 and 30, neither branch sets advice, so print would have nothing to print.
Notice the last line says failed to run the pass manager, not failed to parse. This check runs in a later step, after Mojo has understood your code, so it’s often the error you see after fixing the simpler ones.
What it means
Section titled “What it means”Initialized means “has a value”. In Mojo, var advice: String declares a variable without giving it a value yet. That’s allowed, but Mojo tracks every path through the function and makes sure the variable gets a value before anyone reads it. Python would run this code and maybe crash later with UnboundLocalError, only on the days when the temperature is mild. Mojo refuses to build it.
A variable also becomes uninitialized when you move its value out with ^. After keep(bag^), bag is empty: the list now belongs to keep. The initialization state page of the Mojo manual explains how Mojo tracks both cases.
How to fix it
Section titled “How to fix it”Fix 1: Give the variable a starting value
Section titled “Fix 1: Give the variable a starting value”Often the simplest fix is a default value right where you declare the variable:
def main(): var temp = 18 var advice = "Enjoy the day" if temp > 30: advice = "Stay inside" elif temp < 5: advice = "Wear a coat" print(advice)Output:
Enjoy the dayThe same goes for counters: var total: Int followed by total += n in a loop gives this error, because the first += reads total before it has a value. Write var total = 0.
Fix 2: Set it in every branch
Section titled “Fix 2: Set it in every branch”If there’s no sensible default, make sure every path sets the variable. Usually that means adding the missing else:
def main(): var temp = 31 var advice: String if temp > 30: advice = "Stay inside" elif temp < 5: advice = "Wear a coat" else: advice = "Enjoy the day" print(advice)Output:
Stay insideWith the else, Mojo can see that advice always gets a value, so it accepts var advice: String with no starting value. See Mojo If/Else.
Fix 3: Don’t use a value after you moved it
Section titled “Fix 3: Don’t use a value after you moved it”The second kind of uninitialized value comes from ^:
def keep(var items: List[String]): print("kept", len(items))
def main(): var bag: List[String] = ["pen", "book"] keep(bag^) print(len(bag))bag.mojo:8:14: error: use of uninitialized value 'bag' print(len(bag)) ^bag.mojo:6:9: note: 'bag' declared here var bag: List[String] = ["pen", "book"] ^mojo: error: failed to run the pass managerThe message doesn’t say “moved”, but that’s what happened: bag^ on line 7 gave the list to keep. Two ways out. Do your own work before the move:
def keep(var items: List[String]): print("kept", len(items))
def main(): var bag: List[String] = ["pen", "book"] print(len(bag)) keep(bag^)Output:
2kept 2Or, if you need the list afterwards too, pass a copy: keep(bag.copy()). And if the function only needs to read the list, it shouldn’t take it as var at all: a plain items: List[String] argument borrows it, and you call keep(bag) with no ^. See Mojo Transfer and Mojo Argument Conventions.
Fix 4: Don’t move inside a loop
Section titled “Fix 4: Don’t move inside a loop”A move in a loop works on the first pass and leaves nothing for the second:
var bag: List[String] = ["pen"]for _ in range(2): keep(bag^) # error: use of uninitialized value 'bag'The error points at the ^ on that same line, which is confusing until you remember the loop: the second time round, bag is already gone. Pass bag.copy() inside the loop, or create a fresh list inside the loop body so every pass has its own.
Where you’ll usually see it
Section titled “Where you’ll usually see it”var x: Typewithout a value, then anifwithoutelse, amatchthat doesn’t set it in everycase, or a loop that might run zero times.- Counters declared without
= 0, then+=in a loop. - After
^, in the same function or in the next pass of a loop. - In a struct’s
__init__. If you forget to set a field, the message is worded differently:'self.y' is uninitialized at the implicit return from this function. Set every field in every initializer, or use@fieldwise_init. See Mojo Structs.
Related errors
Section titled “Related errors”- value of type ‘X’ cannot be implicitly copied: the error that usually comes first and leads you to add
^. - use of unknown declaration ‘x’: the variable doesn’t exist at all (often because it was declared inside a block).
- implicit declaration of ‘x’ is not allowed: you assigned without declaring.
- All Mojo error pages: the full list.
Practice
Section titled “Practice”1. Grade every score
Section titled “1. Grade every score”This function should return a letter for any score, but it doesn’t build. Fix it so main prints A, B and C.
def grade(score: Int) -> String: var letter: String if score >= 90: letter = "A" elif score >= 75: letter = "B" return letter
def main(): print(grade(95)) print(grade(80)) print(grade(40))Hint: which score never sets letter?
Show solution
def grade(score: Int) -> String: var letter: String if score >= 90: letter = "A" elif score >= 75: letter = "B" else: letter = "C" return letter
def main(): print(grade(95)) print(grade(80)) print(grade(40))Output:
ABCScores under 75 matched neither branch, so letter had no value at return. The else covers every other case. var letter = "C" at the top would work too.
- The error means a variable might not have a value where you read it.
- Look at both marked lines: declared here and used here, and check every path in between.
- Give it a starting value, or set it in every branch (add the
else). - After
x^the variable is empty. Use it before the move, passx.copy(), or don’t take it asvar. - A move inside a loop fails on the second pass.
Next up: expression must be mutable, the error for changing something you’re only allowed to read.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Initialization state in the Mojo manual: how Mojo tracks when a value is ready to use.
- Ownership in the Mojo manual: moving values with
^and what happens to the old variable. - Variables in the Mojo manual: declaring a variable now and setting it later.
- Mojo Ownership: our lesson on who owns a value and when it moves.