Why `as_ref` and `as_mut` differs in lifetime elision rule?


#1

Code is as follows:

trait Fun {}
struct Funny;
impl Fun for Funny {}


fn bar(_: &Fun) {}
fn foo(_: &mut Fun) {}

fn main() {
  let mut x : Box<Fun> = Box::new(Funny);
  bar(x.as_ref());
  foo(x.as_mut());
}

When it comes to x.as_mut(),the compiler complains error:xdoes not live long enough

This works well:

let temp = x.as_mut();
foo(temp);

But x.as_ref() statement doesn’t need to do that.

What’s more, I find that if the trait is bounded by 'static, the error is gone.

trait Fun : 'static {}

All of these seems like magic to me. Can someone explain why this happens? Thanks in advance.


#2

Seems like a bug. Also working:

foo(x.as_mut() as &mut Fun);

Casting to the same type should never be necessary, no?


#3

Since there are no more replies here, I’d just report this as an issue at https://github.com/rust-lang/rust