Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Yeah in Rust it's not up to the compiler whether generic code is monomorphized or dynamic dispatched, it's part of the language.

A monomorphized function looks like this:

    fn f1<T: Display>(v: &T) -> String {
        format!("{}", v)
    }
A dynamic dispatched function looks like:

    fn f2(v: &dyn Display) -> String {
        format!("{}", v)
    }
Note that we've added the dyn keyword, which tells rust to treat this as a trait object and use dynamic dispatch.

This is actually separate from boxing (these examples are just using normal unboxed references), although typically you would use trait objects with boxing as unboxed trait objects are awkward to work with.

See https://godbolt.org/z/PvM3ox for an example of the compilation: we get two versions of f1 specialized for u32 and u64, but just one for f2.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: