Understanding generics in rust


Pardon, I am newbie in RUST .
I was going through the code of crate lettre and found a struct of the type mentioned below

pub struct Client<S: Write + Read = NetworkStream>

Could you please suggest why there is "=NetworkStream"
I understand this bit Client<S: Write + Read
but don’t understand “=NetworkStream”

Basically, I wish to understand the below

enum WR{

pub struct TestStruct<S: W + R = WR>{

Searching online does not provide much help .

Many thanks


It’s basically a default type that is used if no other type has been specified, so just writing TestStruct would be equivalent to TestStruct<WR>. HashMap<K, V> is a good example of this. It does actually have a third type parameter that you can omit.


I am not sure about the default type.
in above example pub struct Client<S: Write + Read = NetworkStream>
NetworkStream is an enum and there are impls for Read and Write
For example
impl Read for NetworkStream{}
impl Write for NetworkStream{}

So what i understand is either i have to provide a impl for Read and Write or provide an impl for NetworkStream , is it a correct statement ?

Basically NetworkStream = Read + Write,
if above case is valid then why even provide “+ NetworkStream” ?


No, it says that Client can work with any type S that implements Write and Read, but if you don’t specify what type S is, it will pick NetworkStream for you. So, if you have a type MyAwesomeStream that implements Read and Write, then you can use it with Client like so: Client<MyAwesomeStream>. If you don’t have any special stream and is fine with using a NetworkStream, you don’t have to specify it (as in Client<NetworkStream>) and can just write Client.

When reading the generics S is the name of the type parameter (generic), : Write + Read is the required traits, and = NetworkStream is the value of S if you don’t specify anything else. It’s just like how optional function parameters works in some languages: some_function(paramA, paramB = 10). Calling some_function(5) is the same as calling some_function(5, 10).


Ah, now it make sense . Thank you very much.
I code in java .
Rust is a new and exciting land for me.


thank you for the enlightenment


Cheers and good luck!

Although the original poster seems satisfied, I suspect some users still might be confused. This code confused me until I made the following change, and then its meaning was obvious:


pub struct Client<S: Write + Read = NetworkStream>


pub struct Client<S = NetworkStream>

Users of languages like Python and C# will recognize this syntax for default argument values: Rust just applies it to types.