FAQ - Help and questions

How do Java and C# generics differ from Rust generics?

#porting#generics#javapublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Java erases type arguments after compiling, so List of String and List of Integer are one class at run time. C# keeps them. Rust compiles a separate copy per type, with the real size known, and checks the code against trait bounds when it is written. The three models differ in what you can do with T inside the generic.

Checked with rustc 1.93.0, OpenJDK 17.0.18, .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#

The syntax of generics looks alike in the three languages, so ports tend to carry their habits over. The habits do not all survive, because the implementations differ.

JavaC#Rust
Type argument at run timeErasedKeptReplaced by one compiled copy per type
new T() inside the genericNot allowedAllowed with where T : new()Through a trait: T::default() with T: Default
int as a type argumentNot allowed; boxed Integer is usedAllowed, no boxingAllowed; any type
ConstraintT extends Comparable<T>where T : IComparable<T>T: PartialOrd
What is checked, and whenBody checked once against boundsBody checked once against constraintsBody checked once against bounds
Size of a value of type TAlways a referenceValue types have their own sizeKnown per copy: size_of::<T>()

Java, compiled and run with OpenJDK 17.0.18: both lists have the same class, and a value of the wrong type that sneaks in through a raw type is only caught when it is read.

java
List<String> s = new ArrayList<>();
List<Integer> i = new ArrayList<>();
System.out.println(s.getClass() == i.getClass());   // true
List raw = s;
raw.add(42);                       // allowed after erasure (warns when compiling)
try { String x = s.get(0); } catch (ClassCastException e) { System.out.println("ClassCastException at the read"); }
text
true
ClassCastException at the read

C#, .NET SDK 10.0.302:

csharp
Console.WriteLine(typeof(List<int>) == typeof(List<string>));
Console.WriteLine(typeof(List<int>));
Console.WriteLine(new List<string>().GetType().GetGenericArguments()[0]);
static T Make<T>() where T : new() => new T();
Console.WriteLine(Make<int>());
text
False
System.Collections.Generic.List`1[System.Int32]
System.String
0

Rust, rustc 1.93.0. The generic function knows the real type, including its size, and "construct a T" goes through a trait:

src/main.rsrust
use std::any::type_name;
use std::mem::size_of;

fn describe<T>() -> String {
    format!("{} is {} bytes", type_name::<T>(), size_of::<T>())
}

fn main() {
    println!("{}", describe::<Vec<u8>>());
    println!("{}", describe::<(u8, u64)>());
    println!("{}", describe::<Option<u32>>());
    println!("{}", describe::<[u16; 5]>());
    // Rust builds a separate copy of a generic function for each type it is used with:
    // size_of::<T>() inside describe is a constant in each copy.
    let f: fn() -> String = describe::<u8>;
    let g: fn() -> String = describe::<u64>;
    println!("{}", f() != g());
    // no `new T()` and no reflection: construction goes through a trait
    fn make<T: Default>() -> T { T::default() }
    println!("{:?} {:?}", make::<i32>(), make::<String>());
}
text
alloc::vec::Vec<u8> is 24 bytes
(u8, u64) is 16 bytes
core::option::Option<u32> is 8 bytes
[u16; 5] is 10 bytes
true
0 ""

Where this matters in a port: Java code that depends on a runtime type check of T (instanceof T is impossible, but Class<T> tokens are passed around) needs an explicit parameter or a trait method in Rust. C# code that uses typeof(T) or reflection to choose behaviour should become a trait implemented for each type. Java collections of boxed numbers become Vec<i32> and lose the boxing cost and the possibility of null elements.

How to do it#

  1. For each generic class, write a generic struct or function and list what its body does to T. Each operation is a trait bound (see the thread on templates for the table).
  2. Replace new T(), T.default and static abstract members by a trait with an associated function.
  3. Replace instanceof and casts on T by a trait method, or by an enum of the possible types.
  4. Replace wildcards (List<? extends Shape>) with a generic parameter bound by a trait, or with &[Box<dyn Shape>].

Common mistakes#

  • Looking for a common base class Object. Rust has no universal base type; use dyn Any only for the rare case of real run-time typing.
  • Expecting variance rules like List<? super T>. Rust uses lifetimes and traits instead.
  • Adding bounds to the struct definition that only some methods need. Put bounds on the impl blocks or methods that use them.

Is there anything like reflection to inspect T?#

Not in the Java or C# sense. type_name and size_of exist, as above, and Any allows a checked downcast. Behaviour that depends on the type belongs in a trait.

Do Rust generics make the executable larger?#

Each used type gets its own copy of the code. This thread did not measure the effect on any program.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet