4 ms·
> In c the callers isn’t choosing typically. The author of some library or api decides this for you. Tbf this applies to Rust too. If the author writes fn
by K0nserv 9mo ago
> In c the callers isn’t choosing typically. The author of some library or api decides this for you.
Tbf this applies to Rust too. If the author writes
fn foo(bar: Box<dyn BarTrait>)
they have forced the caller into dynamic dispatch.
Had they written
fn foo(bar: impl BarTrait)
the choice would've remained open to the caller
- nicoburns 9mo agoRight, but almost all APIs in Rust use something like fn foo(bar: impl BarTrait) and AFAIK it isn't possible to write that in C (though C++ does allow this kind of thing).
- bfrog 9mo agoC++ you either use templates or classes and virtuals. In either case the caller doesn't get to decide.
- Seattle3503 9mo agoInteresting, there isn't some way to have a template that is polymorphic over virtuals?
- Maxatar 9mo agoIn C++ you do it the other way around, have a single class that is polymorphic over templates. The name of this technique within C++ is type-erasure (that term means something else outside of C++). Examples of type erasure in C++ are classes like std::function and std::any, and normally you need to implement the type erasure manually, but there are some library that can automate it to a degree, such as [1], but it's fairly clumsy. [1] https://www.boost.org/doc/libs/latest/doc/html/boost_typeerasure.html https://www.boost.org/doc/libs/latest/doc/html/boost_typeera...
- bfrog 9mo agoIt's neat this is a thing I guess, but I agree it looks fairly clumsy compared to the Rust answer.
- bsaul 9mo agohow do apis typically manage to actually « use » the « bar » of your example, such as storing it somewhere, without enforcing some kind of constraints ?
- steveklabnik 9mo ago"BarTrait" is the constraint. This is monomorphized for every type you pass in, in short.
- Maxatar 9mo agoIf you need to store the value then you have no choice but to take in a dyn trait.
- steveklabnik 9mo agoDepending on exactly what you mean, this isn't correct. This syntax is the same as <T: BarTrait>, and you can store that T in any other generic struct that's parametrized by BarTrait, for example.
- marcosdumay 9mo ago> you can store that T in any other generic struct that's parametrized by BarTrait, for example Not really. You can store it on any struct that specializes to the same type of the value you received. If you get a pre-built struct from somewhere and try to store it there, your code won't compile.
- steveklabnik 9mo agoCan you show me what you’re talking about? I don’t understand what you mean. I’ll add a code example of what I mean in a bit.
- steveklabnik 9mo agoHere's what I'm talking about: https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=257b78a2c837c0217da5b8d1cd993f93 https://play.rust-lang.org/?version=stable&mode=debug&editio...