Question Details

No question body available.

Tags

rust

Answers (1)

Accepted Answer Available
Accepted Answer
March 7, 2026 Score: 4 Rep: 66,071 Quality: Expert Completeness: 60%

This is an interaction between type inference and type coercion.

In the working case,

let clone = Rc::clone(&struct1);
struct2.addchild(clone);

The Rc::clone produces a Rc. It is not influenced by the addchild call below because there's nothing to infer - &struct1 is well typed. Then the Rc is coerced to Rc when passing it to addchild. This is a valid coercion.

In the non-working case,

struct2.addchild(Rc::clone(&struct1));

The Rc::clone is evaluated in a context that is expecting a Rc. And thus &struct1 must be a &Rc. This is type inference bubbling up. However, &struct1 is a &Rc which cannot be coerced to a &Rc.

The difference in coercions is subtle. The case with the reference is not possible because it can't refer to the original Rc. The Rc itself needs to be coerced.


Is there a way to get it done straight in the call to addchild()?

In this case you can introduce an as cast like so:

struct2.addchild(Rc::clone(&struct1) as Rc);

This will inhibit the type inference from bubbling up to the Rc::clone.