26 ms·
Abstraction without overhead: traits in Rust
- bkeroack 12y agoThere is always overhead when adding abstractions--the only question is whether you pay at runtime or at compile time. C++ (and presumably Rust) choose the latter, Python and Go choose the former.
- steveklabnik 12y agoYes, in these discussions, the overhead being referred to is runtime overhead. There's also overhead in the sense of complexity for the programmer, which isn't really either of those two.
- humanrebar 12y ago> There's also overhead in the sense of complexity for the programmer Well, from the programmers' perspectives there are both read-time and write-time overheads. In C++-land, the discussion about the new (to C++) 'auto' keyword is about the trade-offs between the two.
- SamReidHughes 12y agoC++ chooses both kinds, with templates and virtual functions. Rust does too.
- Dewie3 12y agoIf you want to be really pedantic, there is also the choice between "runtime overhead" and "code overhead" (code specialization). And why not mention the overhead of the programmer foregoing these "short cuts" and hand-coding it herself.
- comex 12y agoThat first one ain't pedantic; C++ code on the whole tends to generate a lot of assembly bloat with inlined methods and template instantiations, and while executable size probably isn't that important for most use cases, it is for quite a few.
- Dewie3 12y agoIt is pedantic in the sense that "overhead" in a programming context will most of the time mean some kind of runtime overhead, unless noted otherwise.
- halayli 12y agoC++ traits, templates, and non-virtual classes have no overhead.
- Manishearth 12y agoTechnically Rust (and C++, IIRC) choose both, but the mindsets of most Rust(/C++) programmers/libraries is to use lower cost abstractions wherever possible. Rust provides features and libraries that provide a dynamic alternative to many different statically checked things; eg trait objects, cell types (internal mutability), shared pointers, etc. The difference is in the mindset: Most Rust programmers will hem and haw at having to use Box<Trait> until we don't have any other viable alternative (with Rust and its enums, there usually are many better ways to do it with lower cost). Java/Go libraries are completely okay with using dynamic dispatch everywhere. While writing Java code I won't be concerned about using an interface type or `Object` or whatever because zero-cost abstractions are not Java's thing. Of course, if there is a static alternative I will still prefer it, but I won't be too bothered if I just stick with `Object`.
- haberman 12y agoGreat article. The main bit of new information for me was that while Rust supports dynamic dispatch, its implementation has a noticeable difference from C++. In C++, the vtable pointer is in the object itself. In Rust, it's stored inside what is essentially a "fat pointer." Pointers to traits ("trait objects") are actually two pointers: the pointer to the vtable and the pointer to the actual object. This seems to have one major downside (pointers are twice as big), but lots of upsides: - allows traits to be implemented for existing types, as opposed to C++ where the type's declaration has to list all base classes. - allows a type to be used through dynamic dispatch while allowing users who don't need this to avoid the vtable overhead. - one less indirection in the call sequence for dynamic dispatch. I like it a lot overall, though the idea of 16-byte pointers on 64-bit architectures does make me slightly queasy.
- pcwalton 12y agoIt also makes multiple inheritance (which Rust has, through Java-like interfaces) easy to implement, and fast at runtime. The virtual inheritance of C++ is a real mess, by contrast [1]. [1]: http://www.phpcompiler.org/articles/virtualinheritance.html http://www.phpcompiler.org/articles/virtualinheritance.html Edit: I don't mean to bash C++ here, BTW; the skinny-pointer approach has a lot of benefits when all you need is single inheritance (and there are early-stage proposals to add it to Rust too). But I don't think it works well for multiple inheritance.
- deleted 12y ago[deleted]
- deleted 12y ago[deleted]
- fmstephe 12y agoI apologise in advance that this may not be most appropriate place to ask this question. I am looking for a Rust tutorial. It looks like there was one, but it was deprecated in favour of 'the book'. But 'the book' doesn't seem to have a tutorial yet. Are there any tutorial's running through how to build some small piece of working software. I found the Golang tutorial, where you build a very basic blog extremely enjoyable. Does Rust have anything similar? https://golang.org/doc/articles/wiki/ https://golang.org/doc/articles/wiki/ Thanks
- deleted 12y ago[deleted]
- coolsunglasses 12y agoTypeclasses benefit from the same "zero runtime overhead" in Haskell (but not Scala). This is particularly important in non-strict languages where inlining is a more prominent aspect of making code performant. Fortunately, GHC is a lot easier to understand WRT optimizations than gcc. You revert to the OOP-style vtables if existential quantification is introduced because you have to pack code with the data, rather than being able to inline the data from a statically known index of methods into the concrete call-sites. As it stands, I'm more likely to want Clean-style uniqueness typing in Haskell for a non-GC'd life-cycle for memory than I am to use Rust, but it's nice to see what we can accomplish with linear types baked into the compiler. Wish regions hadn't been abandoned, but it seems like somebody wanted Rust pushed into becoming a product quickly.
- cwzwarich 12y agoHaskell type classes can not be implemented with zero runtime overhead in all cases, because it is possible to have an unbounded number of instances at runtime for a single type class. The Rust equivalent will just fail at compile time (of the trait implementation, not the trait definition) due to a recursion error.
- deleted 12y ago[deleted]
- gue5t 12y agoCould you describe some of the upsides of regions as compared to Rust-style lifetimes and borrowck?
- kibwen 12y ago> Wish regions hadn't been abandoned, but it seems like > somebody wanted Rust pushed into becoming a product quickly. No idea what you're referring to here. Lifetimes are entirely based on the regions literature, and four frigging years of design iteration is hardly "pushed into becoming a product quickly". :P
- 12y ago
- megaman821 12y agoFor being a lower level language, Rust's abstractions really make feel closer to a higher level language than to C. It will be even more so if HKT's land.
- ajanuary 12y agoHKT = Higher-Kinded Polymorphism [1] [1] http://www.hydrocodedesign.com/2014/04/02/higher-kinded-types/ http://www.hydrocodedesign.com/2014/04/02/higher-kinded-type...
- EugeneOZ 12y ago> Traits are interfaces So why not use "interface" keyword?
- masklinn 12y agoBecause trait is a much better word for it: https://en.wikipedia.org/wiki/Trait_(computer_programming) https://en.wikipedia.org/wiki/Trait_(computer_programming)
- EugeneOZ 12y agoSo in Rust traits can include full methods bodies, not only signatures?
- evanpw 12y agoYes: http://rustbyexample.com/trait.html http://rustbyexample.com/trait.html
- pcwalton 12y agoYes. The feature has been proposed for Java too: "defender methods". Originally I resisted them on the grounds of not being necessary, but they're used all over now. Being able to supply a default implementation is extremely useful.
- oldmanjay 12y agoQuick correction: Java 8 does have defender methods.
- EugeneOZ 12y agoThanks to all for explanations! :) And now I think Traits are traits, but can be used as interfaces too :)
- kzrdude 12y agodefault method implementations makes traits behave like mixins, it's very useful (and it is a form of code reuse).
- pron 12y ago> What you do use, you couldn’t hand code any better. ... given you have no information about runtime behavior other than the static code. How to achieve "zero-cost abstractions" is, as usual, a design tradeoff. Rust -- like C++ -- lets you choose in your code whether you'd like to pay for an abstraction or not. This does produce good machine code, but has two costs: 1/ the language gets more complicated and the programmer needs to be aware of what she's paying for, and 2/ you might end up paying for stuff you end up not using (for example, all button listeners might end up being the same type, and a vtable adds unnecessary cost), so that the generated code is only optimal if you have no other information about runtime behavior. There's another way to add zero-cost abstractions: have a single simple abstraction and a JIT to figure out at runtime -- based on observed behavior -- what the optimal machine code is. This is what the JVM does. All method calls are virtual from the programmer's perspective, and no choice needs to be made ahead of time. At runtime, the JIT views the class hierarchy and usage, and decides whether a specialized, inlined version of a function is produced or whether a vtable is actually necessary (HotSpot even makes a special case when there are exactly two implementations, replacing the vtable with an `if`). If runtime behavior changes (a new type of listener is added or even new code is loaded at runtime that adds another implementation), the JIT will notice, reconsider and recompile. So in Java, virtual or even interface method calls are also zero-cost, even though you have no choice about using them; the decision on how to implement the abstraction is done by the (JIT) compiler at runtime. This, too, is a tradeoff -- a simpler language and truly optimal code taking into consideration not only static consideration but actual runtime behavior -- at the cost of a possibly significant warmup time and possible non-optimal "mistakes" by the JIT.
- Narishma 12y agoI wouldn't call that zero-cost. It's more like variable-cost, which could be even worse than always doing virtual calls in some application types.
- pron 12y agoThe average case is always as expensive or less than a virtual call. But yes, the JIT most certainly introduces unpredictability, which may be unsuitable for hard realtime applications (hard realtime Java programs employ AOT compilation for those classes that require absolute predictability).
- nathan_long 12y ago"new traits can be implemented for existing types (as with Hash above). That means abstractions can be created after-the-fact, and applied to existing libraries." Sounds a bit like a Ruby monkey patch. What happens in case of conflict - my trait adds a .hash method, but there already was one?
- phaylon 12y agoTrait methods are only visible when the trait is in scope. So a conflict would only appear when both traits are imported and the method is called, in which case you'll have to disambiguate.
- nathan_long 12y agoCool, thanks for explaining. :) Would it be a compile-time or runtime error?
- phaylon 12y agoIt would be a compile-time error saying (in essence) "multiple applicable methods in scope" and giving you a list of the available methods.
- nathan_long 12y agoAwesome!