I'm facing some strange behavior when passing an Rc<dyn Trait>
as a function argument. The following code demonstrates the problem.
use std::rc::Rc;
trait Trait {}
struct Struct {}
impl Trait for Struct {}
fn function(_t: Rc<dyn Trait>) {}
fn main() {
let n = Rc::new(Struct {});
// ok
let r = Rc::clone(&n);
function(r);
// error, why?
// function(Rc::clone(&n));
}
If I store the Rc
in a temporary variable, everything works fine. But if I try to call Rc::clone
directly within the function call, I get the following error.
|
19 | function(Rc::clone(&n));
| ^^ expected trait object `dyn Trait`, found struct `Struct`
|
= note: expected reference `&std::rc::Rc<dyn Trait>`
found reference `&std::rc::Rc<Struct>`
Struct
implements Trait
. Why do I get this error?