trait-concept

Rust Generic associated types (GATs)

A generic associated type is an associated type with its own parameters. A borrowed view can vary with the lifetime of each borrow of the owner, rather than requiring one fixed reference lifetime for the whole implementation. Expected output (not executed): draft Why: The returned view is tied to the borrow of Note; the bound allows Self to be valid for the selected lifetime. Common mistake: Assuming the GAT extends the lifetime of the underlying Note.

Formal Syntax & Structure

rust syntaxrust
type View<'a> where Self: 'a;

Working Example

Example Snippetrust
trait Viewable {    type View<'a> where Self: 'a;    fn view(&self) -> Self::View<'_>;}struct Note(String);impl Viewable for Note {    type View<'a> = &'a str where Self: 'a;    fn view(&self) -> Self::View<'_> { &self.0 }}fn main() {    let note = Note(String::from("draft"));    println!("{}", note.view());}
Rust Reference