From trait strategy for big structs

Hello,

When I have two big structs StructA and StructB and I write a From implementation, is it better to use references? How does it work internally in Rust?

impl From<StructB> for StructA

or

impl From<&StructB> for StructA

because of the parameter in the fn from(). I do not want a stack copy of StructB when calling StructA::from().

Thanks

Notionally, From<StructB> will move the StructB to StructA::from's stack frame and then do the conversion, while From<&StructB> will only copy the &StructB to StructA::from's stack frame.

But this notion ignores inlining and other optimizations, and probably shouldn't be your primary motivator. Or if moving StructAs around is a large concern,[1] consider using Box<StructA> instead.

The implementations do different things and there's no good answer to "which is better." Generally, if both were available, you'd use From<StructA> when you no longer needed ownership of the StructA and From<&StructA> when you did still need ownership of the StructA.


  1. heh ↩︎

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.