How can I achieve this OOP functionality in Rust?


While tinkering with the Godot game engine, I came across this piece of code:

class Ball extends KinematicBody2D:

func process(delta):
    if Input.is_action_pressed('ui_right'):
        velocity.x += 1
    move_and_collide(velocity * delta)

I realized I have no idea how I would implement this in any post-OOP language (Rust, Go etc).

I assume the engine's part looks something like
_2d_body.process(delta); _2d_body.render();

I can define a trait (interface in Go) with a method process(), but then I won't have access to the object's fields. And I need to be able to modify velocity, position, etc.

There's currently a discussion about adding fields to traits, but there must be another way.

This is used very often in games, GUI development, etc.


First mistake you are doing, is trying to implement Java/C#/even C++ OOP thinking in Rust. Rust implement some objective model, but its very different from common OOP (the closest I know is C++ standard library model, but its still not very close).

In this very case, KinematicBody2D would be a Trait with process function, and Ball will be struct implementing it. Problem is what is Input here. As long as global state is not good idea, I would rather pass this object into object function (possibly composed with other utilities into some Context struct - possibly only keeping references to context items).

However OOP attitude in general fails in game development, and in Rust it fails harder and earlier. Consider ECS paradigm - there is very good Rust implementation:, and also there is engine based on it (where you can look how input and similar problems are solved in ecs):

Jumping on the ECS bandwagon here ... Be sure to watch the RustConf 2018 closing keynote by Catherine West (and read the associated blog post) where she describes what ECS is and why you should use it for games.