Move/Borrow Semantics for .NET / Unity
Runtime/FancyStuff/RustSharp.cs
(c) 2025 Sator Imaging, Licensed under the MIT License https://github.com/sator-imaging/Unity-Fundamentals
Rust-like move/borrow semantics helper for .NET / Unity providing runtime protection by
throwing NullReferenceException. Note that it doesn't provide compile time protection.
Basic Usage
// absolute ownership should be stored in readonly field.
readonly AbsoluteOwnership<int[]> _arrayOwnership;
// foo takes ownership thus bar ownership will be nullified.
foo._arrayOwnership.Take(bar._arrayOwnership);
// if method takes int[], first you need to move ownership.
var rawData = foo._arrayOwnership.Move(); // ownership is nullified
var result = DoSomething(rawData);
// and then take back ownership.
foo._arrayOwnership.Take(ref result); // result is nullified
// for limited lifetime usage, it can be implicitly converted to Borrow<T>.
// * Borrow<T> is ref struct
DoSomething(foo._arrayOwnership);
// Borrow has `Read` and `Clone()` to express semantics.
// there is not functional difference between those semantic expressions.
T DoSomething(Borrow<int[]> array)
{
for (int i = 0; i < array.Read.Length; i++)
{
array.Read[i] = i;
}
return array.Clone();
}