0

What are the differences between fn(b: &mut Box<dyn Trait>) and fn<T: Trait>(b: &mut T) in Rust?

What is the difference in memory usage and why?

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
  • @IbraheemAhmed Actually no, I shouldve been more clear. I'm more interested in the difference of memory usage. – Michelangelo Dec 15 '20 at 22:10
  • 2
    I think that's covered in the linked question. But there's no difference in the _amount_ of memory used (save for a couple of pointers) - the box just has an extra pointer indirection via the heap – Peter Hall Dec 15 '20 at 22:11
  • The generic function has no overhead (see the Traits section of the TRPL) where the one with Box has one pointer indirection of overhead. Also, did you mean to write `Box`? – Brady Dean Dec 15 '20 at 22:12
  • 1
    There are multiple differences between these two things (note that you could also write `fn(b: &mut dyn Trait)` or `fn(b: &mut Box)`, with still different semantics). The difference between `&mut` and `Box` is described in the answer that's already linked; the difference between `` and `dyn Trait` is addressed in questions such as [What makes something a “trait object”?](/q/27567849/3650362). – trent Dec 15 '20 at 22:23
  • 1
    Also see [How to write a Rust function that takes an iterator?](/q/34969902/3650362) (`Iterator` being an example of a trait) – trent Dec 15 '20 at 22:24
  • 1
    Memory usage is... complicated to analyze, because these are semantically different signatures; you might as well ask whether a function that takes `f64` uses more memory than one that takes `i64`... it depends on the function. – trent Dec 15 '20 at 22:26
  • @trentcl PeterHall BradyDean Thanks for all the given input and links, I've done a bit of research and have read the links and have eventually found this link https://doc.rust-lang.org/book/ch17-02-trait-objects.html and have gained a bit more understanding about the subject. Thanks again. – Michelangelo Dec 15 '20 at 23:10

0 Answers0