Option and generic

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 !

You could write a function that takes an A and returns an S<A, A>:

impl<A> S<A, A> {
    fn new_single(a: A) -> S<A, A> {
        S { a, b: None }
    }
}

fn main() {
    let x = S::new_single(0.0);
}
1 Like

Thank that's exactly what I was looking for !

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.