Why the two same type have different behavior?

Hi, rust expert

I just found a very strange issue. I have a type Option<&T> returned from a function, With two different way to get the type, One is compiled, another is failed with type not match :rofl:

Is this a compiler bug?

Not compile

self.arr.get(0) 

Compiles

        if let Some(r) = self.arr.get(0) {
            Some(r)
        } else {
            None
        }

Here is the code:

Because &S will automatically be converted to &dyn T, but Option<&S> is not automatically converted to Option<&dyn T>.

1 Like

emm... I'm not very understand, Both self.arr.get(0) and Some(r) have the same type Option<&S>, I don't know how/when &S convert &dyn T happen

The compiler inserts the conversion here:

if let Some(r) = self.arr.get(0) {
    Some(convert_to_dyn(r))
} else {
    None
}

It happens automatically because the compiler can see that the argument passed to Some must be a &dyn T.

1 Like

Thanks for your explanation.

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.