Grandimam
Grandimam
MModular
Created by Grandimam on 4/12/2024 in #questions
Transfer operator inside constructor and moveinit
I have a question regarding using the transfer operator inside constructor and moveinit as shown in this example: https://docs.modular.com/mojo/manual/lifecycle/life#move-constructor
struct MyPet:
var name: String
var age: Int

fn __init__(inout self, owned name: String, age: Int):
self.name = name^
self.age = age

fn __copyinit__(inout self, existing: Self):
self.name = existing.name
self.age = existing.age

fn __moveinit__(inout self, owned existing: Self):
self.name = existing.name^
self.age = existing.age

fn example_movable(owned pet: Pet):
print(pet.name)
struct MyPet:
var name: String
var age: Int

fn __init__(inout self, owned name: String, age: Int):
self.name = name^
self.age = age

fn __copyinit__(inout self, existing: Self):
self.name = existing.name
self.age = existing.age

fn __moveinit__(inout self, owned existing: Self):
self.name = existing.name^
self.age = existing.age

fn example_movable(owned pet: Pet):
print(pet.name)
This confuses me a little as I thought that the transfer operator was to be used only while calling the function or assignment something like this:
var foo = MyPet("a", 10)
var bar = foo^ # this works as expected

example_movable(bar^)
var foo = MyPet("a", 10)
var bar = foo^ # this works as expected

example_movable(bar^)
Now, what does it mean for the dunder methods to use ^ operator for assignment? Does it mean the same thing as mentioned above? I tried asking the bot for help as well, but it seems to think that this is an incorrect way of doing. https://discord.com/channels/1087530497313357884/1228421383206473869/1228426919851327578
11 replies