4 ms·
I've only briefly looked at Rust. How would you handle your Drawable if it needs to store some extra data? Few of the things I use inheritance or composition f
by magicalhippo 6y ago
I've only briefly looked at Rust. How would you handle your Drawable if it needs to store some extra data?
Few of the things I use inheritance or composition for can be implemented without storing some extra data.
As an example, say a buffered Stream, that takes a Stream instance and adds buffered access. This BufferedStream would need to store the buffer data somewhere.
- hderms 6y agoRust has BufWriter/BufReader and I'm not an expert but I think you'd just view it as extension through composition
- magicalhippo 6y agoThat does indeed seem[1] to do regular, naive as per OP, composition. I was just curious what OP was using these traits for, as in my non-Rust experience seldom have the need to compose stuff without storing additional data. [1]: https://doc.rust-lang.org/src/std/io/buffered/bufwriter.rs.html https://doc.rust-lang.org/src/std/io/buffered/bufwriter.rs.h...
- coolreader18 6y agoDrawable is just a trait, a definition of methods that can be abstracted over. If you wanted to store data, you'd do it in the type that Drawable is actually being implemented for, i.e. MyEntity. struct MyEntity { cache: RenderingCache, } impl Drawable for MyEntity { fn draw(&self, canvas: &mut Canvas) { self.cache.draw_cached(canvas, |cache_canvas| { cache_canvas.render(ASSET); }); } } const ASSET: Asset = load_asset("foo.png");
- magicalhippo 6y agoThanks, that is very clear. Think Rust differs enough that it's a bit hard for me to draw direct comparisons with my primary languages, but with the emphasis on interfaces like that it does seem like a nicer way to implement extension methods.
- smt1 6y agoHere is some nuance with Rust's OOP relative to java/go/c++: https://stevedonovan.github.io/rust-gentle-intro/object-orientation.html https://stevedonovan.github.io/rust-gentle-intro/object-orie... If you know haskell, Rust's traits are very similar to type classes, except it also has c++-like generics (templates) and is primarily expression-based like ocaml. traits vs haskell type classes: trait -> class struct -> data instance -> impl
- qznc 6y agoIf you are used to Java: It's like making a class implementing an additional interface from the outside. class MyEntity { RenderingCache cache; } now MyEntity implements Drawable { void draw(Canvas canvas) { this.cache.draw_cached(canvas ...); } }