Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Guides writing and reviewing idiomatic Rust using Apollo GraphQL's best practices handbook: ownership, errors, performance, testing, docs.
78% 96%+17 ptsof test cases passed
Passed 22 of 23 test cases with the skill, and 18 of 23 without it.
3 of 3 safety checks passed
Not used yet
Static where you can, dynamic where you must
Rust allows you to handle polymorphic code in two ways:
Understanding the trade-offs lets you write faster, smaller and more flexible code.
Every programming language has tools for effectively handling the duplication of concepts. In Rust, one such tool is generics: abstract stand-ins for concrete types or other properties. We can express the behavior of generics or how they relate to other generics without knowing what will be in their place when compiling and running the code.
We use generics to create definitions for items like function signatures or structs, which we can then use with many different concrete data types. Let's first look at how to define functions, structs, enums, and methods using generics. Generics can also be used to implement Type State Pattern and constrain a struct functionality to certain expected types, more on type state on chapter 7.
You might be wondering whether there is a runtime cost when using generic type parameters. The good news is that using generic types won't make your program run any slower than it would with concrete types. Rust accomplishes this by performing monomorphization of the code using generics at compile time. Monomorphization is the process of turning generic code into specific code by filling in the concrete types that are used when compiled. The compiler checks for all occurrences of the generic parameter and generates code for the concrete types the generic code is called with.
impl Trait or <T: Trait>A static dispatch is basically a constrained version of generics, a trait bounded generic, at compile-time it is able to check if your generic satisfies the declared traits.
fn specialized_sum<U: Sum + RandomMapping, T: Iterator<Item = U>>(iter: T) -> U {
iter.map(|x| x.random_mapping()).sum()
}
// or, equivalent, more modern
fn specialized_sum<U: Sum + RandomMapping>(iter: impl Iterator<Item = U>) -> U {
Skills that do similar work, with their benchmark result.
Next to this one in the catalogue, plus more from the same author.