Tutorial by Examples

// Generic types are declared using the <T> annotation struct GenericType<T> { pub item: T } enum QualityChecked<T> { Excellent(T), Good(T), // enum fields can be generics too Mediocre { product: T } }
// explicit type declaration let some_value: Option<u32> = Some(13); // implicit type declaration let some_other_value = Some(66);
Generics types can have more than one type parameters, eg. Result is defined like this: pub enum Result<T, E> { Ok(T), Err(E), }
// Only accept T and U generic types that also implement Debug fn print_objects<T: Debug, U: Debug>(a: T, b: U) { println!("A: {:?} B: {:?}", a, b); } print_objects(13, 44); // or annotated explicitly print_objects::<usize, u16>(13, 44); The bounds must cover a...
Generic functions allow some or all of their arguments to be parameterised. fn convert_values<T, U>(input_value: T) -> Result<U, String> { // Try and convert the value. // Actual code will require bounds on the types T, U to be able to do something with them. } If the compi...

Page 1 of 1