Module lessons (1/2)
Generic Functions and Structs & Turbofish
Avoid duplication with <T> on functions, struct and enum, monomorphization at compile-time and Turbofish ::<T> syntax.
What you'll learn in this lesson
- Generalize functions,
structandimpl<T>blocks with respect to one or more parameters of type (T,U). - Understanding monomorphization: Why Rust generics don't add runtime overhead.
- Resolve inference ambiguities using the Turbofish (
::<T>) syntax.
Overview
When the logic of an algorithm (such as swapping two elements or wrapping an HTTP response) is identical for i32, f64, or String, duplicating the code violates maintainability. Generics allow you to parameterize types while maintaining absolute static security.
A type parameter must be declared in angle brackets immediately after the function name:
Sections covered in this lesson
- 11. Generic functions with
<T> - 22. Struct and parametric
impl<T> - 33. Zero-cost monomorphization and multiple parameters
<K, V> - 44. Turbofish
::<T>when inference is not enough - 5Practical exercises
- 6Check for understanding
Unlock "Generic Functions and Structs & Turbofish" and the full Course Rust curriculum
Avoid duplication with `<T>` on functions, `struct` and `enum`, monomorphization at compile-time and Turbofish `::<T>` syntax.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course Rust plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.