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.
| Java | C# | Rust | |
|---|---|---|---|
| Type argument at run time | Erased | Kept | Replaced by one compiled copy per type |
new T() inside the generic | Not allowed | Allowed with where T : new() | Through a trait: T::default() with T: Default |
int as a type argument | Not allowed; boxed Integer is used | Allowed, no boxing | Allowed; any type |
| Constraint | T extends Comparable<T> | where T : IComparable<T> | T: PartialOrd |
| What is checked, and when | Body checked once against bounds | Body checked once against constraints | Body checked once against bounds |
Size of a value of type T | Always a reference | Value types have their own size | Known 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.
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"); }true
ClassCastException at the readC#, .NET SDK 10.0.302:
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>());False
System.Collections.Generic.List`1[System.Int32]
System.String
0Rust, rustc 1.93.0. The generic function knows the real type, including its size, and "construct a T" goes through a trait:
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>());
}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#
- 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). - Replace
new T(),T.defaultand static abstract members by a trait with an associated function. - Replace
instanceofand casts onTby a trait method, or by anenumof the possible types. - 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; usedyn Anyonly 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
implblocks or methods that use them.
Related questions#
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#
- The Rust Book, "Generic Data Types": https://doc.rust-lang.org/book/ch10-01-syntax.html
- Java Tutorials, "Type Erasure": https://docs.oracle.com/javase/tutorial/java/generics/erasure.html