← Back to context

Comment by whs

1 year ago

In Rust most function take a reference to its argument, which means the ownership is shared. However, you can also pass non-reference to it which indicate that you wish to transfer ownership to the function (of course the caller must be the previous owner). Once the function take ownership there's no way to take it out unless they returned it, so it achieve the effect you're looking for.

I heard some HTTP library used that to expose a state machine, so functions that cause HTTP header to be sent will take ownership and return a new value which no longer expose HTTP headers setter methods.

For freeing memory or resources, the recommended way to do it is in RAII-style, with custom Drop implementation that will get called when the ownership is dropped instead of explicit close() or free()