Misleading “use of uninitialized value” error when fieldwise struct partially transferred

Hi Mojo team,

I am experimenting with the move semantics and encountered an error message that seems misleading. Here is a minimal reproducible example:

@fieldwise_init
struct MyPair:
    var first: List[String]
    var second: List[Int]

    fn get_sum_of_second(self) -> Int:
        return len(self.second)

def main():
    var pair = MyPair(first=["apple", "banana", "cherry"], second=[1, 2, 3, 4])
    var captureList = pair.first^
    var _ = pair.get_sum_of_second()

Error:

/Users/test/test.mojo:12:35: error: use of uninitialized value 'pair.first'
    var _ = pair.get_sum_of_second()
                                  ^
/Users/test/test.mojo:10:9: note: 'pair' declared here
    var pair = MyPair(first=["apple", "banana", "cherry"], second=[1, 2, 3, 4])

In this case, get_sum_of_second() does not use pair.first at all, but the compiler still reports “use of uninitialized value pair.first.”

It seems that after partially transferring pair.first with the ^ operator, the compiler treats the whole struct as partially moved and forbids using it—even if only unaffected fields are accessed. I understand that partial move support is challenging to implement, but perhaps the diagnostic could be clearer, e.g.:

“cannot call method on partially transferred struct (field ‘first’ moved)”

This would make it clearer that the issue is about partial moves rather than actual uninitialized use.

I love Mojo so far—its combination of safety and expressiveness feels fantastic! Just wanted to share this feedback in case it helps improve the user experience.

Thanks for the amazing work!

This is expected behavior. Mojo doesn’t look into the implementation of “get_sum_of_second()” to understand what fields it accesses, so it must assume it touched everything in “self”. We have ideas on how to improve this in the future (allowing a method to say that it only touches a subset of a value passed into it) but these features aren’t able to be prioritized in the near future, so this is expected behavior for now.

Thanks for the clarification! Looking forward to seeing how Mojo evolves in this area!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.