Skip to main content
Module 5 · Lesson 1 of 29/24 in the course~18 min
Module lessons (1/2)

Generic Functions and Structs & Turbofish

Lesson preview5 hands-on exercises readyCourse Rust · Module 5 — Generics and Traits

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, struct and impl<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

  1. 11. Generic functions with <T>
  2. 22. Struct and parametric impl<T>
  3. 33. Zero-cost monomorphization and multiple parameters <K, V>
  4. 44. Turbofish ::<T> when inference is not enough
  5. 5Practical exercises
  6. 6Check for understanding
Pro Lesson · Module 5 — Generics and Traits

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.