Is inout a equivalent system to pass a pointer to the function?
I was wondering if inout is a equivalent system to pass a pointer to the function?
13 Replies
It makes a variable mutable in the scope of the function. So if you pass an Int into a function and add to it it will maintain its new value in the outer scope. inouting a variable is almost universally faster than creating one in the scope passing it out.
quoting the documentation:
https://docs.modular.com/mojo/programming-manual.html#mutable-arguments-inout
"Notice that we don’t call this argument passing “by reference.” Although the inout convention is conceptually the same, we don’t call it by-reference passing because the implementation may actually pass values using pointers."
Modular Docs - Mojo🔥 programming manual
A tour of major Mojo language features with code examples.
Everything is said in a way that implies you're not supposed to make assumptions about the actual implementation
The really interesting part is that I have yet to encounter anything that requires using the
__moveinit__
method.what do you mean?
It is required for move only types
Like a socket
If you copied a socket the destructors would try close it multiple times
things you would usually use classes for
I don't think Mojo has the apparatus to check borrowing yet is what I am saying. I have used inout, and owned and never had to add a
__moveinit__
to my array struct.I'm pretty sure I got compile errors
did you use
@value
?Though I haven't tried using async which is the only place it would matter.
No I don't use value unless i need everything it adds.
This is odd, I have to try remove it
but I'm pretty sure you just don't need moveinit if you have a copyinit
I don't know what you're doing differently
commenting out moveinit does break my code
Whereas when I add it back it works.
Copying a struct with pointers inside would lead to a double free, though in this case I made a reference counted smart pointer so the only consequence would be shared mutable state.