FAQ - Help and questions

C# classes are shared by reference and structs are copied. What does Rust do?

#porting#csharp#ownershippublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

In C# assigning a class variable makes a second name for the same object, while assigning a struct copies it. Rust does neither silently. Assignment moves the value, a copy needs Clone or Copy, and a second name for the same object is an explicit reference, Rc, or Rc with RefCell.

Checked with rustc 1.93.0, .NET SDK 10.0.302, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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 writeC# classC# structRust
var b = a;b and a are the same objectb is a copylet b = a; moves a (a is unusable) unless the type is Copy
independent copya.Clone() if you wrote itvar b = a;a.clone(), or implicit when the type is Copy
a second name for the same objectvar b = a;reflet b = &a; (borrow) or Rc::clone(&a) (shared owner)
change through the second nameworksworks 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):

csharp
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; }
text
class : a=2 b=2
struct: s=1 t=2

The Rust version of "two names, one object" is explicit, and so is the copy (rustc 1.93.0):

src/main.rsrust
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);
}
text
copy: a=1 b=2
shared: 2 2
15

The 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#

  1. For each C# struct (small, plain data), write a Rust struct and derive Clone and Copy if all fields are Copy. Copies are then implicit, as in C#.
  2. 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 &T or &mut T.
  3. If several parts of the program really hold the same object and change it, use Rc<RefCell<T>> on one thread and Arc<Mutex<T>> across threads.
  4. If a method received an object and changed it so that the caller sees the change, give the Rust method &mut self or a &mut T parameter. The caller then needs &mut x at the call site, so the change is visible in the code.
  5. Replace ref and out parameters with &mut T or 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 Copy on a type that holds a String or Vec. It does not compile, because those own heap data; use Clone.
  • Passing a struct by value when the method only needs to read it, and then being unable to use it afterwards. Take &T.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet