3 ms·
> Rust has a feature called traits. Traits are a way of doing compile-time static dispatch, and can also be used to do runtime dispatch (although in practice th
by tomjakubowski 10y ago
> Rust has a feature called traits. Traits are a way of doing compile-time static dispatch, and can also be used to do runtime dispatch (although in practice that’s rarely useful.)
Hmm, I dunno about that. If you need to keep a collection of callbacks, that would most certainly be a collection of Fn/FnMut trait objects, that is this:
struct Thing {
callbacks: Vec<Box<FnMut(i32) -> i32>>
}
and not this:
struct Thing<F> where F: FnMut(i32) -> i32 {
callbacks: Vec<F>
}
The same applies for any use of traits where the exact impl to be used is not known until runtime, like choosing a behavior from some set of behaviors in a configuration file.
- leshow 10y agoHow does that contradict what the post says? A trait object (the boxed fn in your example) is used for dynamic dispatch. OP says "can also be used". It sure looks like the Fn trait is being used for dynamic dispatch in that example.
- khuey 10y agoHe's objecting to the "in practice rarely useful" bit.