Difference between below as_ref() implementations?

fn as_ref<T>(opt: &Option<T>) -> Option<&T> {
    match *opt {
        Some(ref x) => Some(x),
        None => None,
    }
}

and

fn as_ref<T>(opt: &Option<T>) -> Option<&T> {
    match opt {
        Some(x) => Some(x),
        None => None,
    }
}

I see that the source code implements former.

I don't think there is a difference, but the second one I don't think would have been accepted in the 2015 edition, which is probably why the source uses the first one.

1 Like

I think it's better in this case to use the explicit function even with match ergonomics, because in the second version there's no difference between as_ref() and as_mut().

2 Likes

Lots of code in the standard library is very old. So it's pretty easy to find code that wouldn't be written the same way today -- like code doing .offset(d as isize) where today it'd be .add(d).

1 Like

yeah looks like mutable references works with match ergonomics as well.

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.