How do I make object oriented like code that works?

I wanna be able to write a ui engine like morphic.js, but I wanna do it in rust

“Object oriented” is a pretty overloaded term, and everyone seems to have a different idea of what it means.

Can you be more specific about which object-oriented design patterns you are interested in? Some OO patterns work pretty well in Rust, but others are quite cumbersome.

1 Like

First of all: do you want to write a UI engine that works with <canvas> elements like morphic.js does or it was just an example and you want something different?

I don't care about the HTMLCanvasElement objects, I just want to have a similar internal representation

I'd like to have something that uses inheritance and object pointers

Inheritance of state is basically the "big no" in terms of Rust not supporting it well enough to be worth trying to hack it in in it's current state. "Object pointers" is a fairly ambiguous term, but it's probably shared mutability, something like Arc<Mutex<T>>, this is also a pain enough that you want to avoid it if at all possible.

You can fake inheritance of behavior with traits somewhat well enough, though you don't get to call the super method so you need to do a bit more busy work to actually share logic like that.

Really, this all just doesn't seem necessary though: if you're trying to represent drawable objects like on a canvas all you should care about being about to draw them and what size they are, etc.: that's all just one trait you can put in a Box (or just an enum). What do you need inheritance for?

3 Likes

I'm not sure what you're looking for exactly in terms of "object pointers", but I'd assume what you're looking for are references.

#[derive(Debug)]
struct Foo(u8);

fn main() {
    let myfoo: Foo = Foo(11);
    let ref_to_myfoo: &Foo = &myfoo;
    println!("{:#?}",ref_to_myfoo);
}

As for inheritance, Rust doesn't really have such a thing, but depending on your needs there are various patterns that might help. Traits can be thought of in a similar fashion to interfaces (as one might know from Java) and can have default implementations for their methods which can be overridden. If Foo is just Bar with a few extra fields, you can make Foo contain a Bar. There's been a lot of discussion about inheritance already which might be able to help you:

2 Likes