Default value for generic type

How to get default value for generic type, that is:

struct S<T>
{
val: T
}
impl<T> S<T>
{
pub fn new()->Self
{
S{val: ????}//need default for T
}
}

Thanks

Do you want to bound T by Default? If so your default value will be T::default(). Not all types have a default value so I think adding the bound (struct S<T:Default>) is what you want.

Thanks, yep that's exactly what I wanted.

You can use the Default trait:

impl<T> S<T> where T: Default
{
    pub fn new() -> Self {
        S { val: T::default() }
    }
}
2 Likes