Module 9 · Traits & generics
9.2Generics, bounds & where
How Rust generics name what a type parameter must be able to do with trait bounds and where clauses, how they compile to one copy per type, and when to pick a concrete type, a generic or impl Trait.
On this page
- Concept map
- A type parameter and its bound
- No bound, no methods
- Operators need bounds too
- Several bounds and where clauses
- When the caller names the type
- Generic types and conditional impls
- Blanket impls: one impl for every type with a bound
- Which one should I use?
- Under the hood
- Common pitfalls
- Try it yourself
Concept map
| Concept | TypeScript | C# | Rust |
|---|---|---|---|
| A type parameter limited to types with an ability | <T extends Shape> | <T> with where T : IShape | <T: Shape> |
| Several bounds on one type parameter | T extends Shape & Named | where T : IShape, INamed | T: Shape + Display, or the same in a where clause |
Using >= on a type parameter | Allowed for any T, even objects, which are converted to primitives at run time | Needs a constraint, such as IComparable<T> and CompareTo | Needs the operator's trait as a bound: T: PartialOrd |
| Methods that exist only for some type arguments | A this: parameter on the method | An extension method with its own constraint | A conditional impl block: impl<T: PartialOrd> Pair<T> |
| What the compiled program has | One function; T is erased | Real types at run time; one shared copy for reference types, one per value type | One copy per type the function is used with; no type information at run time |
TypeScript generics look almost the same as Rust’s: function larger<T extends Shape>(a: T, b: T): T becomes fn larger<T: Shape>(a: T, b: T) -> T.C# generics look almost the same as Rust’s: static T Larger<T>(T a, T b) where T : IShape becomes fn larger<T: Shape>(a: T, b: T) -> T. The syntax carries over. Three things change. A Rust type parameter can do nothing until a bound says what it can do, and that includes operators such as >= and printing with {}. A bound can turn methods on for some type arguments and not others. And the compiler turns each generic function into a separate, specialized copy for every type you call it with, where TypeScriptC# erases T and runs one function for every typeshares one compiled copy between all reference types (value types do get their own).
A type parameter and its bound
larger takes two shapes of the same type and returns the bigger one, as that same type:
interface Shape {
area(): number;
}
class Square implements Shape {
side: number;
constructor(side: number) {
this.side = side;
}
area(): number {
return this.side * this.side;
}
}
function larger<T extends Shape>(a: T, b: T): T {
return a.area() >= b.area() ? a : b;
}
const big = larger(new Square(2), new Square(3));
console.log(`side ${big.side}`);var big = Larger(new Square(2), new Square(3));
Console.WriteLine($"side {big.Side}");
static T Larger<T>(T a, T b) where T : IShape => a.Area() >= b.Area() ? a : b;
interface IShape
{
int Area();
}
class Square(int side) : IShape
{
public int Side { get; } = side;
public int Area() => Side * Side;
}trait Shape {
fn area(&self) -> u32;
}
struct Square {
side: u32,
}
impl Shape for Square {
fn area(&self) -> u32 {
self.side * self.side
}
}
fn larger<T: Shape>(a: T, b: T) -> T {
if a.area() >= b.area() { a } else { b }
}
fn main() {
let big = larger(Square { side: 2 }, Square { side: 3 });
println!("side {}", big.side);
}Output
side 3
<T: Shape>declares a type parameterTand its bound:Tcan be any type that implementsShape. Read the:as extendswhere T :.-> Tgives the caller back the type it passed in.bigis aSquare, sobig.sideworks. A function returning “some shape” couldn’t offer that.Tis inferred from the arguments, as in TypeScriptC#. Here it’sSquare.
No bound, no methods
Inside the function, the compiler only lets you do what the bounds promise. Drop : Shape and a.area() is no longer allowed, even though every type you’d ever pass has an area method:
fn larger<T>(a: T, b: T) -> T {
if a.area() >= b.area() { a } else { b }
}Rust doesn't compile this: error E0599
error[E0599]: no method named `area` found for type parameter `T` in the current scope
--> main.rs:2:10
|
1 | fn larger<T>(a: T, b: T) -> T {
| - method `area` not found for this type parameter
2 | if a.area() >= b.area() { a } else { b }
| ^^^^ method not found in `T`
|
= help: items from traits can only be used if the type parameter is bounded by the trait
help: the following trait defines an item `area`, perhaps you need to restrict type parameter `T` with it:
|
1 | fn larger<T: Shape>(a: T, b: T) -> T {
| +++++++
error[E0599]: no method named `area` found for type parameter `T` in the current scope
--> main.rs:2:22
|
1 | fn larger<T>(a: T, b: T) -> T {
| - method `area` not found for this type parameter
2 | if a.area() >= b.area() { a } else { b }
| ^^^^ method not found in `T`
|
= help: items from traits can only be used if the type parameter is bounded by the trait
help: the following trait defines an item `area`, perhaps you need to restrict type parameter `T` with it:
|
1 | fn larger<T: Shape>(a: T, b: T) -> T {
| +++++++TypeScriptC# works the same way: TypeScript reports Property 'area' does not exist on type 'T'C# reports CS1061, 'T' does not contain a definition for 'Area'. The generic body is checked once, against its bounds, not again for each type it’s called with. The compiler’s help suggests the bound to add.
Operators need bounds too
In Rust, operators are trait methods: >= and < come from PartialOrd, == from PartialEq, + from Add. So a generic function that compares its arguments needs a bound that says they can be compared:
function maxOf<T extends number | string>(a: T, b: T): T {
return a >= b ? a : b;
}
console.log(maxOf(3, 7));
console.log(maxOf("pear", "apple"));Console.WriteLine(MaxOf(3, 7));
Console.WriteLine(MaxOf("pear", "apple"));
static T MaxOf<T>(T a, T b) where T : IComparable<T> => a.CompareTo(b) >= 0 ? a : b;fn max_of<T: PartialOrd>(a: T, b: T) -> T {
if a >= b { a } else { b }
}
fn main() {
println!("{}", max_of(3, 7));
println!("{}", max_of("pear", "apple"));
}Output
7 pear
Without T: PartialOrd, the comparison is an error, and the help suggests exactly that bound:
fn max_of<T>(a: T, b: T) -> T {
if a >= b { a } else { b }
}Rust doesn't compile this: error E0369
error[E0369]: binary operation `>=` cannot be applied to type `T`
--> main.rs:2:10
|
2 | if a >= b { a } else { b }
| - ^^ - T
| |
| T
|
help: consider restricting type parameter `T` with trait `PartialOrd`
|
1 | fn max_of<T: std::cmp::PartialOrd>(a: T, b: T) -> T {
| ++++++++++++++++++++++TypeScript is far more lenient here. It accepts >= on any T, objects included, and at run time converts both objects to the string "[object Object]", so a >= b is always true. This version has no constraint at all, compiles, and returns the smaller square:
class Square {
side: number;
constructor(side: number) {
this.side = side;
}
}
function maxOf<T>(a: T, b: T): T {
return a >= b ? a : b;
}
console.log(maxOf(new Square(2), new Square(3)).side);Output
2
That’s why the TypeScript version above limits T to number | string by hand.
C# rejects a >= b on an unconstrained T too (CS0019). The usual fix is IComparable<T> and CompareTo, as above. Generic math interfaces such as IComparisonOperators<T, T, bool> let you write >= itself, but string doesn’t implement them. A Rust bound like PartialOrd is the operator: i32, f64, &str and String all implement it.
The bound is checked at the other end too. A Square has no PartialOrd impl, so passing two squares doesn’t compile:
struct Square {
side: u32,
}
fn main() {
let big = max_of(Square { side: 2 }, Square { side: 3 });
}Rust doesn't compile this: error E0277
error[E0277]: can't compare `Square` with `Square`
--> main.rs:6:15
|
6 | let big = max_of(Square { side: 2 }, Square { side: 3 });
| ^^^^^^ no implementation for `Square < Square` and `Square > Square`
|
= help: the trait `PartialOrd` is not implemented for `Square`
note: required by a bound in `max_of`
--> main.rs
|
| fn max_of<T: PartialOrd>(a: T, b: T) -> T {
| ^^^^^^^^^^ required by this bound in `max_of`
help: consider annotating `Square` with `#[derive(PartialOrd)]`
|
1 + #[derive(PartialOrd)]
2 | struct Square {
|Caught at compile timeComparing things that can't be compared
A generic function can only use >= on types that say how to compare themselves, so comparing two shapes, two users or two lists by accident is a compile error, not a wrong answer at run time. To make Square comparable, add #[derive(PartialEq, PartialOrd)] above it, which compares the fields in order. Standard traits covers it.
Several bounds and where clauses
Join bounds with +. Here report needs a shape it can also print with {}:
interface Shape {
area(): number;
}
class Square implements Shape {
side: number;
constructor(side: number) {
this.side = side;
}
area(): number {
return this.side * this.side;
}
toString(): string {
return `square ${this.side}`;
}
}
function report<T extends Shape>(shape: T): string {
return `${shape} has area ${shape.area()}`;
}
console.log(report(new Square(3)));Console.WriteLine(Report(new Square(3)));
static string Report<T>(T shape) where T : IShape => $"{shape} has area {shape.Area()}";
interface IShape
{
int Area();
}
class Square(int side) : IShape
{
public int Area() => side * side;
public override string ToString() => $"square {side}";
}use std::fmt;
trait Shape {
fn area(&self) -> u32;
}
struct Square {
side: u32,
}
impl Shape for Square {
fn area(&self) -> u32 {
self.side * self.side
}
}
impl fmt::Display for Square {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "square {}", self.side)
}
}
fn report<T: Shape + fmt::Display>(shape: &T) -> String {
format!("{shape} has area {}", shape.area())
}
fn main() {
println!("{}", report(&Square { side: 3 }));
}Output
square 3 has area 9
TypeScriptC# needs only one constraint, because every valueobject can be turned into text with toString()ToString(). Rust types can’t be printed with {} until they implement Display, so report asks for it. With two of your own traits, you’d write T extends Shape & Namedwhere T : IShape, INamed in TypeScriptC#, and T: Shape + Named in Rust.
When bounds get long, or there are several type parameters, move them into a where clause after the signature. It means exactly the same thing. Here two different shape types each need both bounds, and the last function shows the impl Trait form of report:
struct Rectangle {
width: u32,
height: u32,
}
impl Shape for Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
impl fmt::Display for Rectangle {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "rectangle {}x{}", self.width, self.height)
}
}
fn report_both<A, B>(first: &A, second: &B) -> String
where
A: Shape + fmt::Display,
B: Shape + fmt::Display,
{
let total = first.area() + second.area();
format!("{first} and {second}: {total} in total")
}
fn report(shape: &(impl Shape + fmt::Display)) -> String {
format!("{shape} has area {}", shape.area())
}
fn main() {
let square = Square { side: 3 };
let rect = Rectangle {
width: 2,
height: 5,
};
println!("{}", report_both(&square, &rect));
println!("{}", report(&rect));
}Output
square 3 and rectangle 2x5: 19 in total rectangle 2x5 has area 10
A and B are separate type parameters, so report_both accepts a square and a rectangle together. &(impl Shape + fmt::Display) needs the parentheses, so that the + clearly belongs inside the &.
When the caller names the type
Sometimes T doesn’t appear in any argument, so there’s nothing to infer it from. Then the caller names it with ::<>, a piece of syntax nicknamed the turbofish. This uses the Shape trait with unit() and scaled() from Traits:
interface Shape {
scaled(factor: number): Shape;
area(): number;
}
interface ShapeType {
unit(): Shape;
}
class Square implements Shape {
side: number;
constructor(side: number) {
this.side = side;
}
static unit(): Square {
return new Square(1);
}
scaled(factor: number): Square {
return new Square(this.side * factor);
}
area(): number {
return this.side * this.side;
}
}
function areaAtScale(type: ShapeType, factor: number): number {
return type.unit().scaled(factor).area();
}
console.log(areaAtScale(Square, 3));Console.WriteLine(AreaAtScale<Square>(3));
static int AreaAtScale<T>(int factor) where T : IShape<T> => T.Unit().Scaled(factor).Area();
interface IShape<TSelf> where TSelf : IShape<TSelf>
{
static abstract TSelf Unit();
TSelf Scaled(int factor);
int Area();
}
class Square(int side) : IShape<Square>
{
public static Square Unit() => new(1);
public Square Scaled(int factor) => new(side * factor);
public int Area() => side * side;
}trait Shape {
fn unit() -> Self;
fn scaled(&self, factor: u32) -> Self;
fn area(&self) -> u32;
}
struct Square {
side: u32,
}
impl Shape for Square {
fn unit() -> Self {
Self { side: 1 }
}
fn scaled(&self, factor: u32) -> Self {
Self {
side: self.side * factor,
}
}
fn area(&self) -> u32 {
self.side * self.side
}
}
fn area_at_scale<T: Shape>(factor: u32) -> u32 {
T::unit().scaled(factor).area()
}
fn main() {
println!("{}", area_at_scale::<Square>(3));
}Output
9
T::unit() calls the associated function of whatever type T is, and area_at_scale::<Square>(3) says which. Leave out ::<Square> and the compiler asks for a type annotation. TypeScript can’t do this with a type argument, because T is erased: areaAtScale<Square>() would have no class to call unit on at run time. So the TypeScript version passes the class itself as a value.This is the job C# static abstract members were added for, and the call looks the same: AreaAtScale<Square>(3). The same syntax shows up with the standard library: "42".parse::<u32>() names the type to parse into.
Generic types and conditional impls
Structs and enums take type parameters too, and so do impl blocks. An impl block can also add its own bounds, so a method exists only for the type arguments that meet them. Here every Pair<T> has new, but only a pair of comparable values has largest:
class Pair<T> {
first: T;
second: T;
constructor(first: T, second: T) {
this.first = first;
this.second = second;
}
largest<U extends number | string>(this: Pair<U>): U {
return this.first >= this.second ? this.first : this.second;
}
}
const numbers = new Pair(3, 7);
const words = new Pair("pear", "apple");
console.log(numbers.largest());
console.log(words.largest());var numbers = new Pair<int>(3, 7);
var words = new Pair<string>("pear", "apple");
Console.WriteLine(numbers.Largest());
Console.WriteLine(words.Largest());
class Pair<T>(T first, T second)
{
public T First { get; } = first;
public T Second { get; } = second;
}
static class PairExtensions
{
public static T Largest<T>(this Pair<T> pair) where T : IComparable<T> =>
pair.First.CompareTo(pair.Second) >= 0 ? pair.First : pair.Second;
}struct Pair<T> {
first: T,
second: T,
}
impl<T> Pair<T> {
fn new(first: T, second: T) -> Self {
Self { first, second }
}
}
impl<T: PartialOrd> Pair<T> {
fn largest(&self) -> &T {
if self.first >= self.second {
&self.first
} else {
&self.second
}
}
}
fn main() {
let numbers = Pair::new(3, 7);
let words = Pair::new("pear", "apple");
println!("{}", numbers.largest());
println!("{}", words.largest());
}Output
7 pear
impl<T> Pair<T>looks like it saysTtwice, and it does:impl<T>declares a type parameter for the block, andPair<T>uses it. Read it as “for every typeT, here are methods forPair<T>”.impl<T: PartialOrd> Pair<T>reads “for everyTthat can be compared”. APair<Square>is still a valid type, with anewfunction, but calling.largest()on it doesn’t compile: the method exists, and its bound isn’t met.
TypeScript gets the same effect with a this: parameter, which limits which pairs may call the method.A C# method can constrain its own type parameters, but it can’t add a constraint to the class’s T, so the C# version uses an extension method with its own where clause. In Rust it’s an ordinary impl block, and a type can have as many as you like, each with different bounds.
Blanket impls: one impl for every type with a bound
The same idea works for traits. impl<T: Display> Shout for T implements Shout for every type that implements Display, all at once:
use std::fmt::Display;
trait Shout {
fn shout(&self) -> String;
}
impl<T: Display> Shout for T {
fn shout(&self) -> String {
format!("{}!", self.to_string().to_uppercase())
}
}
fn main() {
println!("{}", "hello".shout());
println!("{}", 42.shout());
}Output
HELLO! 42!
This is called a blanket impl. The standard library uses one to give every type that implements Display a to_string method, which is why implementing Display is enough to get .to_string(). The nearest C# feature is a generic extension method, Shout<T>(this T value) where T : .... It adds a method, but T doesn’t become an implementer of any interface, so code that requires one won’t accept it.TypeScript has nothing like it: you can’t make every type with some ability gain a new method.
Which one should I use?
Every function that works with “a shape” faces this choice. Pick the simplest option that does the job.
| What | When | Why | How |
|---|---|---|---|
| Concrete type | Only one type is ever passed. | Simplest signature and simplest errors. Make it generic later, when a second type turns up. | fn area(square: &Square) -> u32 |
impl Trait parameter | Any type with the ability will do, and nothing else in the signature mentions that type. | Compiles to the same code as a named generic, with less to read. | fn report(shape: &impl Shape) -> String |
Named type parameter <T: Trait> | The same type appears in two places (two parameters, or a parameter and the return value), or the caller must name it with ::<>. | Only a name can tie two positions to one type, or be filled in by the caller. | fn larger<T: Shape>(a: T, b: T) -> T |
where clause | The bounds are long, or there are several type parameters. | Same meaning as inline bounds, and the signature stays readable. | fn report_both<A, B>(…) -> String where A: Shape + Display, B: Shape + Display |
| Conditional impl | Some methods only make sense for some type arguments. | The method exists exactly when its bound is met, with no run-time check. | impl<T: PartialOrd> Pair<T> { fn largest(&self) -> &T … } |
| Blanket impl | Every type with one ability should get your trait. | One impl covers types you haven’t seen yet, including other crates’ types. | impl<T: Display> Shout for T { … } |
The first three rows as questions; the first “yes” gives the answer:
Is only one type ever passed?
YesNoA concrete type:
fn area(square: &Square) -> u32Make it generic when a second type needs the same function.Does one call need values of different types together, such as a list of mixed shapes, or a type chosen while the program runs?
YesNoA trait object,
dyn ShapeA generic picks one type per call, when you compile. The next lesson, impl Trait vs. dyn Trait, covers trait objects.Must the same type appear twice (two parameters, or a parameter and the return value), or must the caller name it?
YesNoA named type parameter:
fn larger<T: Shape>(a: T, b: T) -> TMove long bounds into awhereclause.Otherwise:
impl Trait:fn report(shape: &impl Shape) -> String. It compiles to the same code as a named generic.
Rule of thumb: write the concrete type first. When a second type needs the same function, take &impl Trait. Switch to a named <T: Trait> when the type has to appear twice or the caller must choose it, and move the bounds into where once they stop fitting on one line. impl Trait vs. dyn Trait covers mixed-type lists and returning impl Trait.
Under the hood
Rust compiles generics by monomorphization: for every type a generic function is used with, the compiler writes a separate copy of it with that type filled in. These three calls produce three functions, max_of::<i32>, max_of::<f64> and max_of::<&str>:
let n = max_of(3, 7); // max_of::<i32>
let x = max_of(2.5, 1.5); // max_of::<f64>
let w = max_of("pear", "apple"); // max_of::<&str>
assert_eq!((n, x, w), (7, 2.5, "pear"));In the i32 copy, a >= b is a single integer comparison, and the optimizer can inline the whole call. There’s no allocation, no type check at run time and no indirect call. That’s the “zero-cost” in zero-cost abstractions: generic code runs as fast as code you’d write by hand for each type. The price is paid when you build: every distinct type adds a copy, so heavily generic code compiles more slowly and makes a bigger binary. A library’s generic functions ship in a form the compiler can still fill in, so the copy for your types is generated when your crate is compiled.
Here’s how that compares with TypeScriptC#:
| TypeScriptC# | Rust | |
|---|---|---|
| Compiled copies of a generic function | One. Types are erased, so the JavaScript that runs has no T at all.One in IL. The JIT makes one native copy shared by all reference types, and a specialized copy for each value type (int, double, your structs). | One per type it’s used with, made when you compile. |
Is T known at run time? | No. You can’t write new T() or check x instanceof T.Yes. Generics are reified: typeof(T) and new T() (with a new() constraint) work. | No. Each copy has its type filled in, so there’s nothing left to look up. |
How a T value is stored | As a JavaScript value, like everything else.Unboxed: a List<int> holds the ints themselves. | Inline, at T’s real size. |
The last row shows up in memory. Pair<u8>, Pair<u64> and Pair<&str> are three different types with three different sizes:
assert_eq!(size_of::<Pair<u8>>(), 2);
assert_eq!(size_of::<Pair<u64>>(), 16);
assert_eq!(size_of::<Pair<&str>>(), 32); // each &str is a pointer and a length| Value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | Size |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Pair<u8> | first1 byte | second1 byte | 2 bytes | ||||||||||||||||||||||||||||||
Pair<u64> | first: u648 bytes | second: u648 bytes | 16 bytes | ||||||||||||||||||||||||||||||
Pair<&str> | first: ptr8 bytes · pointer | first: len8 bytes | second: ptr8 bytes · pointer | second: len8 bytes | 32 bytes | ||||||||||||||||||||||||||||
Today, on a 64-bit target. Pair of u8 takes 2 bytes: first and second, 1 byte each. Pair of u64 takes 16 bytes: first and second, 8 bytes each. Pair of &str takes 32 bytes: first is a pointer and a length, 8 bytes each, and second is another pointer and length. Each Pair type stores its two values inline at their real size, with nothing added.
When you’d rather have one compiled function that works through a pointer, at the cost of an indirect call, Rust has trait objects. That trade-off is the subject of impl Trait vs. dyn Trait.
Common pitfalls
Common pitfallOne type parameter means one type
larger<T: Shape>(a: T, b: T) takes two values of the same type. A square and a rectangle are both shapes, but they aren’t the same T:
struct Square {
side: u32,
}
struct Rectangle {
width: u32,
height: u32,
}
fn larger<T: Shape>(a: T, b: T) -> T {
if a.area() >= b.area() { a } else { b }
}
fn main() {
let rect = Rectangle {
width: 2,
height: 3,
};
larger(Square { side: 2 }, rect);
}Rust doesn't compile this: error E0308
error[E0308]: mismatched types
--> main.rs:19:32
|
19 | larger(Square { side: 2 }, rect);
| ------ ------------------ ^^^^ expected `Square`, found `Rectangle`
| | |
| | expected all arguments to be this `Square` type because they need to match the type of this parameter
| arguments to this function are incorrect
|
help: the return type of this call is `Rectangle` due to the type of the argument passed
--> main.rs:19:5
|
19 | larger(Square { side: 2 }, rect);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^----^
| |
| this argument influences the return type of `larger`
note: function defined here
--> main.rs:10:4
|
10 | fn larger<T: Shape>(a: T, b: T) -> T {
| ^^^^^^ - ---- ---- this parameter needs to match the `Square` type of `a`
| | |
| | `b` needs to match the `Square` type of this parameter
| `a` and `b` both reference this parameter `T`T became Square from the first argument, so the second must be a Square too. If the types may differ, give each its own parameter: <A: Shape, B: Shape>, or &impl Shape twice, since each impl Trait is a separate type parameter. Then the function can’t return “whichever one”, because there’s no single type to return; return the area instead.
Common pitfallA blanket impl claims every type that fits
After impl<T: Display> Shout for T, bool already implements Shout, because bool implements Display. A second impl for it conflicts:
use std::fmt::Display;
trait Shout {
fn shout(&self) -> String;
}
impl<T: Display> Shout for T {
fn shout(&self) -> String {
format!("{}!", self.to_string().to_uppercase())
}
}
impl Shout for bool {
fn shout(&self) -> String {
String::from("YES!")
}
}Rust doesn't compile this: error E0119
error[E0119]: conflicting implementations of trait `Shout` for type `bool`
--> main.rs:13:1
|
7 | impl<T: Display> Shout for T {
| ---------------------------- first implementation here
...
13 | impl Shout for bool {
| ^^^^^^^^^^^^^^^^^^^ conflicting implementation for `bool`This is coherence from Traits again: at most one impl of a trait per type. Write a blanket impl only when every type with the bound should behave the same way.
Common pitfallBounds on a struct don't carry over to its impl
Coming from C#, where class Pair<T> where T : IComparable<T> covers every method,TypeScript, where class Pair<T extends number> covers every method, it’s tempting to put the bound on the struct. In Rust, every impl block must repeat it, so this fails:
struct Pair<T: PartialOrd> {
first: T,
second: T,
}
impl<T> Pair<T> {
fn first(&self) -> &T {
&self.first
}
}Rust doesn't compile this: error E0277
error[E0277]: can't compare `T` with `T`
--> main.rs:6:9
|
6 | impl<T> Pair<T> {
| ^^^^^^^ no implementation for `T < T` and `T > T`
|
note: required by a bound in `Pair`
--> main.rs:1:16
|
1 | struct Pair<T: PartialOrd> {
| ^^^^^^^^^^ required by this bound in `Pair`
help: consider restricting type parameter `T` with trait `PartialOrd`
|
6 | impl<T: std::cmp::PartialOrd> Pair<T> {
| ++++++++++++++++++++++
error[E0277]: can't compare `T` with `T`
--> main.rs:7:15
|
7 | fn first(&self) -> &T {
| ^^^^ no implementation for `T < T` and `T > T`
|
note: required by a bound in `Pair`
--> main.rs:1:16
|
1 | struct Pair<T: PartialOrd> {
| ^^^^^^^^^^ required by this bound in `Pair`
help: consider restricting type parameter `T` with trait `PartialOrd`
|
6 | impl<T: std::cmp::PartialOrd> Pair<T> {
| ++++++++++++++++++++++The fix is to leave the struct unbounded, struct Pair<T>, and put bounds only on the impl blocks and functions that use them, as Pair does above. That’s the usual Rust style: the type stays usable with anything, and each method asks for what it needs.
Try it yourself
Exercise: port this to Rust
Port this to Rust. cheaper returns whichever of two items costs less, as the type it was given. label describes any item that has a price and can be printed. Write the bounds each function needs, and nothing more.
interface Priced {
cents(): number;
}
class Book implements Priced {
title: string;
price: number;
constructor(title: string, price: number) {
this.title = title;
this.price = price;
}
cents(): number {
return this.price;
}
toString(): string {
return this.title;
}
}
function cheaper<T extends Priced>(a: T, b: T): T {
return a.cents() <= b.cents() ? a : b;
}
function label<T extends Priced>(item: T): string {
return `${item}: ${item.cents()} cents`;
}
const book = cheaper(new Book("Dune", 1299), new Book("Emma", 899));
console.log(book.title);
console.log(label(book));var book = Cheaper(new Book("Dune", 1299), new Book("Emma", 899));
Console.WriteLine(book.Title);
Console.WriteLine(Label(book));
static T Cheaper<T>(T a, T b) where T : IPriced => a.Cents() <= b.Cents() ? a : b;
static string Label<T>(T item) where T : IPriced => $"{item}: {item.Cents()} cents";
interface IPriced
{
int Cents();
}
class Book(string title, int price) : IPriced
{
public string Title { get; } = title;
public int Cents() => price;
public override string ToString() => Title;
}Expected output
Emma Emma: 899 cents
Show a hint
cheaper only calls cents, so T: Priced is enough. label also prints the item with {}, so it needs Priced and Display, written in a where clause. Implement Display for Book where the other versions define a string conversion.
Show a solution
use std::fmt;
trait Priced {
fn cents(&self) -> u32;
}
struct Book {
title: String,
price: u32,
}
impl Priced for Book {
fn cents(&self) -> u32 {
self.price
}
}
impl fmt::Display for Book {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.title)
}
}
fn cheaper<T: Priced>(a: T, b: T) -> T {
if a.cents() <= b.cents() { a } else { b }
}
fn label<T>(item: &T) -> String
where
T: Priced + fmt::Display,
{
format!("{item}: {} cents", item.cents())
}
fn main() {
let dune = Book {
title: String::from("Dune"),
price: 1299,
};
let emma = Book {
title: String::from("Emma"),
price: 899,
};
let book = cheaper(dune, emma);
println!("{}", book.title);
println!("{}", label(&book));
}cheaper returns T, so main gets a Book back and can read book.title. label has two bounds because a Rust type can't be printed until it implements Display; in the other versions every object can already be turned into text. Both functions are compiled once, for Book, because that's the only type they're called with.
Saved in this browser only.