5 ms·
how do apis typically manage to actually « use » the « bar » of your example, such as storing it somewhere, without enforcing some kind of constraints ?
by bsaul 9mo ago
how 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...
- tcfhgj 9mo agosure about that? the struct in which it is stored, could be generic as well
- Maxatar 9mo agoI'm addressing the intent of the original question. No one would ask this question in the case where the struct is generic over a type parameter bounded by the trait, since such a design can only store a homogeneous collection of values of a single concrete type implementing the trait; the question doesn't even make sense in that situation. The question only arises for a struct that must store a heterogeneous collection of values with different concrete types implementing the trait, in which case a trait object (dyn Trait) is required.