How does rust understand whats the output of deref form a reference?

I have implemented Deref for my tuple struct which wraps a string with target str.

struct MyStr(String)
impl Deref for MyStr{
    type Target = str
    fn deref(&self)->&str

And I noticed that I can just pass a reference of my struct to places where &str is required.

How does rust understand how to go to &str from &MyStr

This is called implicit deref coercion. It knows because you're using it in a context where only &str makes sense.

1 Like

The compiler does this by automatically calling <MyStr as Deref>::deref to match the reference type, since the Target matches the desired str. However, if you have done this in the impl Deref itself, you'll have an infinite recursion.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.