Answer#
C# decides copy-or-share by the kind of type: a class is a reference type (assignment shares one object) and a struct is a value type (assignment copies). The decision is made once, in the type's definition, and every use of the type follows it. Rust decides at each use, and says so in the code:
| What you write | C# class | C# struct | Rust |
|---|---|---|---|
var b = a; | b and a are the same object | b is a copy | let b = a; moves a (a is unusable) unless the type is Copy |
| independent copy | a.Clone() if you wrote it | var b = a; | a.clone(), or implicit when the type is Copy |
| a second name for the same object | var b = a; | ref | let b = &a; (borrow) or Rc::clone(&a) (shared owner) |
| change through the second name | works | works with ref | &mut a (one at a time) or Rc<RefCell<T>> |
The two C# lines are the classic surprise (.NET SDK 10.0.302):
var a = new P { X = 1 };
var b = a;
b.X = 2;
Console.WriteLine($"class : a={a.X} b={b.X}");
var s = new S { X = 1 };
var t = s;
t.X = 2;
Console.WriteLine($"struct: s={s.X} t={t.X}");
class P { public int X; }
struct S { public int X; }class : a=2 b=2
struct: s=1 t=2The Rust version of "two names, one object" is explicit, and so is the copy (rustc 1.93.0):
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Debug, Clone)]
struct P {
x: i32,
}
fn main() {
// C# class: var b = a; b.X = 2; changes what a sees as well (one object, two names)
// Rust: `let b = a;` moves; to get two independent values you ask for a copy, to share you say so.
let a = P { x: 1 };
let mut b = a.clone();
b.x = 2;
println!("copy: a={} b={}", a.x, b.x);
let shared = Rc::new(RefCell::new(P { x: 1 }));
let also = Rc::clone(&shared);
also.borrow_mut().x = 2;
println!("shared: {} {}", shared.borrow().x, also.borrow().x);
// a method that changes its argument says so in the signature
fn bump(p: &mut P) { p.x += 10; }
let mut c = P { x: 5 };
bump(&mut c);
println!("{}", c.x);
}copy: a=1 b=2
shared: 2 2
15The first block is what a C# struct does; the second is what a C# class does. In Rust you have to choose, and the choice is visible in the type (P against Rc<RefCell<P>>).
How to do it#
- For each C#
struct(small, plain data), write a Rust struct and deriveCloneandCopyif all fields areCopy. Copies are then implicit, as in C#. - For each C#
class, ask whether the object really has several owners. Often it has one owner and others only use it for a while: pass&Tor&mut T. - If several parts of the program really hold the same object and change it, use
Rc<RefCell<T>>on one thread andArc<Mutex<T>>across threads. - If a method received an object and changed it so that the caller sees the change, give the Rust method
&mut selfor a&mut Tparameter. The caller then needs&mut xat the call site, so the change is visible in the code. - Replace
refandoutparameters with&mut Tor with return values (tuples,Result).
Common mistakes#
- Making everything
Rc<RefCell<T>>to keep the semantics of classes. The cost is run-time borrow checking and possible panics. - Deriving
Copyon a type that holds aStringorVec. It does not compile, because those own heap data; useClone. - Passing a struct by value when the method only needs to read it, and then being unable to use it afterwards. Take
&T.
Related questions#
Is readonly struct or record close to anything in Rust?#
A plain struct with no &mut methods behaves like an immutable value. A C# record corresponds roughly to a struct with #[derive(Debug, Clone, PartialEq)].
What about null for a class variable?#
Option<T>, or Option<Rc<RefCell<T>>> for a shared one.
Sources#
- The Rust Book, "What Is Ownership?": https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html
- The Rust Book, "RefCell<T> and the Interior Mutability Pattern": https://doc.rust-lang.org/book/ch15-05-interior-mutability.html