3 ms·
The day I started (time ago) to learn Rust I had trouble learning to map Error(s) and dynamic dispatching. My first thought was: "if I cannot escape dynamic dis
by scoutt 4y ago
The day I started (time ago) to learn Rust I had trouble learning to map Error(s) and dynamic dispatching. My first thought was: "if I cannot escape dynamic dispatching (for example with crates that use it), I will never understand how to use Rust in embedded, because of Box<T>". And as an embedded C developer, this is something I never understood. For example:
"Values can be boxed (allocated on the heap) by creating a Box<T>" (https://doc.rust-lang.org/rust-by-example/std/box.html https://doc.rust-lang.org/rust-by-example/std/box.html)
But then I see
Box<dyn std::error::Error>
everywhere, for example in https://github.com/oxidecomputer/hubris/search?q=dyn https://github.com/oxidecomputer/hubris/search?q=dyn
Is Box really allocating here? Is the "Rust By Example" text incomplete?
Then I had to stop learning Rust for other reasons, but this doubt really hit me at the time.
- jmillikin 4y agoDynamic dispatch (the `dyn` keyword) and dynamic allocation are distinct in Rust. You'll see Box<dyn SomeTrait> a lot in application-level code because the developer UX of boxed dynamic resembles a GC'd language like Java/Go, but they're not really coupled under the hood. Dynamic dispatch allows you to call trait methods on values without knowing the concrete type of that value, similar to C++ virtual methods or a C-style manually constructed vtable. In an embedded context this will mostly show up as function parameters, since you can't move things around on the stack without knowing their size. You might also see references to a dyn value, like `&dyn SomeTrait` -- this is similar to `Box<dyn SomeTrait>`, but is a borrowed reference and therefore doesn't imply allocation. Your link to the Oxide Hubris repo is misleading you because the hits seem to be pretty much all in build-time helper scripts (`build.rs`) and other minor tooling. You'd want to look through the source of their main binary, which probably wouldn't use allocation just for error propagation.
- scoutt 4y ago> Your link to the Oxide Hubris repo is misleading you Sorry about this. It wasn't intentional. But just to confirm, Box<T> always allocates? So dynamic dispatch is not recommended in embedded, and thus crates that uses dynamic dispatch and/or Box<T>?
- jmillikin 4y agoDynamic dispatch (dyn) in embedded is fine. Dynamic allocation (Box) in embedded is not recommended. `&dyn SomeTrait` is dynamic dispatch without dynamic allocation. `Box<i32>` is dynamic allocation without dynamic dispatch.