4 ms·
Is it possible to use Rust without much necessary usage of generics?
by andrewmcwatters 6y ago
Is it possible to use Rust without much necessary usage of generics?
- steveklabnik 6y agoDefining your own? Absolutely. Using them at all? Basically impossible. The standard (and core) library is entirely built around it.
- andrewmcwatters 6y agoPerhaps Rust can be the language where I force myself to get used to them. In C++ there are stilly plenty of alternatives to not having to use templates. The reason I ask is I've preferred not to use them because I find them slightly more demanding to read. I think that's just a personal bias I need to get over.
- steveklabnik 6y agoYeah you're not alone. Have you used concepts at all yet? Rust's generics are similar to, but different than, C++ templates generally; concepts is the closest thing C++ has to them. That being said, even when you understand them, you can create some monstrosities, just like C++. To connect it back to your original questions, Rust relies heavily on generics because if you want runtime performance, but you also want safety, you pretty much need ways to evaluate safety at compile time, rather than runtime, so you don't have the overhead of runtime checks. This basically implies generics need to exist and be used heavily.
- andrewmcwatters 6y agoI haven't spent any time in C++20, so it's interesting to hear that. I'll try and read more about both. Thanks for your thoughts on this.
- steveklabnik 6y agoAny time. One last tiny bit of overview: templates can currently do a bunch of things that Rust generics can’t. Some of these are things that Rust will be adding in the future, some are not, and some are uncertain. So there’s a lot of parallels but some folks who are very invested in templates say they don’t want to move to Rust yet because we’re missing things they desire.
- gpm 6y agoDepends what you mean I guess. You can certainly write code that doesn't create more generic structs, and needing to create more generic structs when writing simple application plumbing code is relatively rare. On the flip side you also certainly want to use stdlib (and third party) libraries and instantiate generic structs they define. For example a list of T objects is most commonly stored in a Vec<T> where T is a generic, or for a builtin example a fixed sized array is a `[T; N]` where both T and N are generic. There's also approximately no reason to avoid generics. All in all the frequency of use of generics is pretty similar to languages like C++ or Scala.