Rust                
            Merkloos product
        
        
            
    Zoeken…
Verklaring
// 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 }
}
instantiëring
// explicit type declaration
let some_value: Option<u32> = Some(13);
// implicit type declaration
let some_other_value = Some(66);
Meerdere typeparameters
 Generieke typen kunnen meer dan één typeparameters hebben, bijv. Result is als volgt gedefinieerd: 
pub enum Result<T, E> {
    Ok(T),
    Err(E),
}
Begrensde generieke typen
// 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);
 De grenzen moeten alle toepassingen van het type omvatten. Toevoeging wordt gedaan door de std::ops::Add eigenschap std::ops::Add , die zelf invoer- en uitvoerparameters heeft. where T: std::ops::Add<u32,Output=U> stelt dat het mogelijk is om Add T aan u32 en deze toevoeging heeft om te produceren typen U . 
fn try_add_one<T, U>(input_value: T) -> Result<U, String> 
    where T: std::ops::Add<u32,Output=U> 
{
    return Ok(input_value + 1);
}
 Sized gebonden wordt standaard geïmpliceerd. ?Sized bound staat ook unized types toe. 
Algemene functies
Met generieke functies kunnen sommige of alle argumenten worden geparametriseerd.
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.
}
Als de compiler de parameter type niet kan afleiden, kan deze bij aanroep handmatig worden ingevoerd:
let result: Result<u32, String> = convert_value::<f64, u32>(13.5);
Modified text is an extract of the original Stack Overflow Documentation
        Licentie onder CC BY-SA 3.0
        Niet aangesloten bij Stack Overflow