The following genericset program rewrites the
intset example using
generics. Instead of a set of i32 values, it
defines GenericSet<T>, a set whose values have some
type T chosen by the code that uses it. The program is
very close to line-for-line the same as intset; compare the two to
see what changed:
struct GenericSet<T>
stores a Vec<T> instead of a
Vec<i32>.
impl block declares the type parameter too, and every
i32 in a function signature becomes T. Every
IntSet becomes GenericSet<T>.
contains and remove take a reference,
&T, instead of a value. For a String,
passing the value would move it into the function just to look for it,
and the caller could not use it again. insert still takes
a T, because the set needs to own what it stores.
*v,
genericset duplicates it with v.clone().
Copying with *v works for an i32 but not for
a String, which owns heap memory.
main uses the same set with
String values.
One line needs a preview of a later topic. The functions compare values
with == and duplicate them with .clone(), which
not every type allows, so the impl block is written
impl<T: PartialEq + Clone>. PartialEq and
Clone are traits, which we will cover later. For
now, read this as “any type T that can be compared and
cloned.”
This zip file contains the complete crate.