Generics and Bounds
Lesson 37 of 48 in Coddy's Rust for C Developers course.
A generic function names a type parameter instead of choosing one concrete type. Bounds state the operations available on that parameter: PartialEq permits equality, Ord permits total ordering, and Clone permits explicit duplication. Rust checks the function using those promises and specializes calls for concrete types. C often uses macros or void * with callbacks for similar reuse; a cast does not provide the same static check. The generic function here counts adjacent equal pairs without knowing whether the items are numbers or words. Returning an owned item from a borrowed slice may require cloning.
C
#include <stdio.h>
int adjacent_equal(const int *items, int count) {
int matches = 0;
for (int i = 1; i < count; ++i) if (items[i - 1] == items[i]) ++matches;
return matches;
}
int main(void) {
int items[] = {4, 4, 7, 7, 7};
printf("%d\n", adjacent_equal(items, 5));
return 0;
}Rust
fn adjacent_equal<T: PartialEq>(items: &[T]) -> usize {
items.windows(2).filter(|pair| pair[0] == pair[1]).count()
}
fn main() {
println!("{} {}", adjacent_equal(&[4, 4, 7, 7, 7]), adjacent_equal(&["a", "b", "b"]));
}Unconstrained T does not automatically support comparison or copying. Declare only the bounds the algorithm needs.
Challenge
EasyImplement 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));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Rust for C Developers
1First Rust Programs
Run Rust ModulesOutput and CommentsModules and VisibilityBindings and TypesNumbers and CastsRecap: Storage Invoice4Ownership and Borrowing
Ownership and MovesShared BorrowsMutable BorrowsLifetimes and ViewsBorrowing Recap2Decisions and Loops
Boolean ConditionsIf ExpressionsMatch and EnumsLoops and RangesRecap: Charge Gate8Traits and Generic Code
Traits and ContractsGenerics and BoundsTrait ObjectsFunction PointersDerived Value SemanticsTesting Public ContractsScoring Contracts Recap3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record ReadingsPractice on your own: Online Rust compiler