generics - What does this syntax mean (<T=Self>) and when to use it? -


i see things <t=self> or t=() in generic structs/traits. suspect has default types generic type t. couldn't find documentation though.

my questions are:

  • what mean?
  • what variations possible (maybe crazy <t=self: 'static>)?
  • when useful (examples)?

this syntax can used in 2 situations: default type parameters, , associated types. see difference , le use, lets have @ add trait, used define + operator:

pub trait add<rhs = self> {     type output;     fn add(self, rhs: rhs) -> self::output; } 

default type parameters

here, type parameter rhs has default value: self. means that, whenever use trait, value of type parameter default self if omit it. example:

impl add foo { /* ... */ } 

is same as

impl add<foo> foo { /* ... */ } 

likewise,

fn foo<t>(t: t) t: add { /* ... */ } 

is same

fn foo<t>(t: t) t: add<t> { /* ... */ } 

associated types

the trait add has associated type : output. type chosen implementation of trait.

the reason behind not make sense implement add different output types while input types same: once self , rhs known, output type cannot chosen.

this construct used iterators example, when iterate on container, not choose type of values generated iterator: associated type.

it possible select value associated type in where clauses, using foo = bar syntax. example:

fn foo<i>(i: i) i: iterator<item=u8> { /* ... */ } 

this function can work on iterator yielding u8 values.

to sum up

the syntax foo=bar used in definition of generic construct allows set default value type parameter, , used in where clauses allows match on value of associated type.

there no possible variations foo = bar : baz or things that.


Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -