Hi everybody,
I am not sure how to deal with the following situation where I have a generic structure with a Option in it.
pub struct S<A,B>{
a: A,
b: Option<B>,
}
fn main(
)
{
println!("Testing some code :°)");
let x = S{a: 0.0, b: Some(0.0)}; // this works
let x = S{a: 0.0, b: None}; // this do not work
}
I understand wy it is not working, it can't understand which type is B. Here is the full error:
error[E0282]: type annotations needed for `S<f64, B>`
--> src/main.rs:16:11
|
16 | let x = S{a: 0.0, b: None};
| - ^ cannot infer type for type parameter `B` declared on the struct `S`
| |
| consider giving `x` the explicit type `S<f64, B>`, where the type parameter `B` is specified
My question is how to deal with it ? My first idea was to use a custom Option enum, and having a None value which encapsulated a default value anyway so that it can cast the type. But it would be inefficient plus I will loose all the good things that come with the Option enum like unwrap etcc.
In practice in almost all of my instance of this struct, the B type would be A, unless I precise otherwise with the Some.
Is there a way to tel the compiler to fall back to give the type A to B if he find a None ?
Or like implementing automatically
pub struct S<A>{
a: A,
b: Option<A>,
}
from the other structure.
Thanks in advance !