Polyglot CheatSheet - Generics
Last Updated: 2023-02-28
Go
Generic functions:
func Index[T comparable](s []T, x T) int
Generic types:
type List[T any] struct {
next *List[T]
val T
}
Rust
// in function
fn foo<T>(list: &[T]) -> T {
}
// in struct
struct Point<T> {
x: T,
y: T,
}
// in enum
enum Option<T> {
Some(T),
None,
}
// in method
struct Point<T> {
x: T,
y: T,
}
impl<T> Point<T> {
fn x(&self) -> &T {
&self.x
}
}
Java
Java Type erasure: enforcing type constraints only at compile time and discarding the element type information at runtime.