Menu
CoddyTech

Generics and Bounds

Lesson 37 of 48 in Coddy's Rust for C# Developers course.

C# generic constraints specify the operations available for a type parameter. Rust trait bounds serve a similar role, and missing bounds cannot be inferred merely because current callers happen to use a capable type. The examples test whether two supplied values are equal. C# uses an IEquatable<T> constraint; Rust borrows two values under T: PartialEq. The function does not clone or take ownership of its inputs. Rust generally generates specialized code for concrete generic instantiations, while C# uses runtime and JIT strategies that may share code; this implementation detail should not be confused with the source-level contract. A generic parameter denotes one concrete type per instantiation. It does not by itself create a heterogeneous list. Trait objects solve a different problem when concrete types must be hidden behind a common interface at runtime. The equality example requires neither ordering nor returning an owned maximum.

Complete C# program:

using System;
class Program {
    static bool Same<T>(T left, T right) where T : IEquatable<T> { return left.Equals(right); }
    static void Main() { Console.WriteLine(Same("oak", "oak")); }
}

Complete Rust program:

fn same<T: PartialEq>(left: &T, right: &T) -> bool { left == right }
fn main() {
    let left = String::from("oak");
    let right = String::from("oak");
    println!("{}", same(&left, &right));
}
challenge icon

Challenge

Easy

Implement selection::largest<T: Ord + Clone>(items: &[T]) -> Option<T>. Return an owned clone of the greatest element, or None for an empty slice. Do not change the input. The function must work for any type meeting the bounds, including nonnumeric user-defined types. solve reads mode number followed by signed integers, or word followed by ASCII words. Return the greatest number or lexicographically greatest word; return empty if no items follow the mode. Numbers fit i32.

Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.

Your code goes in exercise.rs, selection.rs. main.rs holds the supplied input/output code and cannot be edited.

Try it yourself

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod selection;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // BEGIN PUBLIC API PROBES
assert_eq!(selection::largest(&[-41, -8, -19]), Some(-8));
assert_eq!(selection::largest::<i32>(&[]), None);
let words = vec!["alpha".to_string(), "zebra".to_string(), "beta".to_string()];
assert_eq!(selection::largest(&words), Some("zebra".to_string()));
assert_eq!(words[0], "alpha");
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug)]
struct Rank(i32, String);
let values = vec![Rank(4, "z".to_string()), Rank(8, "b".to_string()), Rank(8, "a".to_string())];
assert_eq!(selection::largest(&values), Some(Rank(8, "b".to_string())));
assert_eq!(selection::largest(&values), Some(Rank(8, "b".to_string())));
    // END PUBLIC API PROBES
    println!("{}", exercise::solve(&input));
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Rust for C# Developers

Practice on your own: Online Rust compiler