ModularM
Modularโ€ข3y agoโ€ข
4 replies
vmois

Owned convention does not destroy variable after transferring ownership

Hello everybody! I am working on a project that has a small exercises to learn Mojo. Currently, I am working on value ownership section and was playing with a code below.

# TASK
# Make file compile with no errors

# I AM NOT DONE

fn take_ptr(owned array: Pointer[Int]):
    array.store(2, 23)


fn main():
    # this line just allocates pointer for 3 integers
    var array = Pointer[Int].alloc(3)

    array.store(0, 1)
    array.store(1, 2)

    # this function call does not need any changes
    take_ptr(array^)

    array.store(2, 2)
    print(array[2])


The issue I have is that this code compiles but to my understanding of owned and ownership operator it shouldn't.

If you take equivalent code for string, it has an error "a is not initialized":

fn take_text(owned text: String):
    text += "๐Ÿ”ฅ"
    return text


fn main():
    var a: String = "mojo"

    take_text(a^)
    print(a)


For equivalent integer code:
fn take_value(owned x: Int):
    x += 2


fn main():
    var x: Int = 1
    take_value(x^)
    print(x)


It throws no error, and value of x is 1.

Can someone please explain if this behaviour is correct or am I missing something? Thank you.
Was this page helpful?