How feasible would it be to support some kind of borrowed/owned reference
system in Julia? Similar to the system in Rust, but maybe not so powerful.
I know it sounds unusual, but I thought it was interesting enough to be
worth a discussion.
The reasons to want it:
- Can be used to support safe, efficient shared memory (for some use cases,
at least)
- Predictable memory usage (most users won't care, but it might be useful
in library code).
- Ownership semantics are very useful for libraries. For example, if you
have destructors which are called as soon as an owned type goes out of
scope, you can safely manage resources allocated by C libraries, and make
it transparent to end users.
- Would expand Julia's appeal to an even wider audience.
Possible implementation:
- Any type T can be allocated as an Owned{T} (maybe using a macro, to make
sure that all parameters are either immutable or owned)
- Any call like "getfield(f::Foo, :b)::Bar" would instead be
"getfield(f::Owned{Foo}, :b)::Borrowed{Bar}"
- Can also do "getfield(f::Borrowed{Foo}, :b)::Borrowed{Bar}"
- Trying to do "setfield(f::Foo, :b, b::Borrowed{Bar})" causes a runtime
error
- Doing "setfield(t::T, :f, b::Owned{Bar})" works, but turns b into a
broken reference, so that subsequent accesses do not work.
- For use with existing code, multiple dispatch would probably need to
treat "Owned{Foo}" the same way it treats "Foo". Either that, or you use
some kind of subtype relationship.
- Destructors just work as follows: "destruct(t::Owned{T}) = # do
whatever". There is an "Any" destructor which does nothing.
Downsides:
- Might confuse some people a lot. It would mostly only be used to
implement libraries though, and by people doing multithreading stuff, which
is already a complex task.
- It is a language feature. A big one. I know you guys don't like adding
language features.
- The multiple dispatch hack sounds like it might wreak havoc.
- Might be too much work for something not relevant enough to your core
goals.
- I have no idea what I'm talking about, so everything I said might be
rubbish :)