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
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() }
}
}
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.