ModularM
Modular3y ago
31 replies
b4rdarian

Confusion with owned integers

I tried the replacing String from the example in the docs and got an error when running build.

Docs example
fn set_fire(owned text: String) -> String:
    text += "🔥"
    return text

fn mojo():
    let a: String = "mojo"
    let b = set_fire(a)
    print(a)
    print(b)

mojo()


My modified example
fn take_ownership_int(owned x: Int) -> Int:
    x += 5
    return x


fn main():
    let x = 10
    let y = take_ownership_int(x)
    print("x = " + String(x) + " and y = " + String(y))


Error
❯ mojo build hello-world/take_ownership.mojo
/path/to/hello-world/take_ownership.mojo:9:26: error: use of uninitialized value 'x'
    print("x = " + String(x) + " and y = " + String(y))
                         ^
/path/to/hello-world/take_ownership.mojo:7:5: note: 'x' declared here
    let x = 10
    ^
mojo: error: failed to run the pass manager

---

If I replace Int with String it builds ok.
fn take_ownership_str(owned x: String) -> String:
    x += " mojo"
    return x


fn main():
    let hello = "hello"
    let hello_mojo = take_ownership_str(hello) 
    print("hello = " + hello + " and hello_mojo = " + hello_mojo)
Was this page helpful?