I want to have a array/list/queue of instances of various struct types that represent events. How can I achieve that? With classes I would have interfaces I guess, but I want to use structs if possible as they seem less complex (and faster?).

Can I wrap each struct with in another struct called something like Entry that in turn can contain the event struct some how, or will that just move the problem?

        import std.stdio;

        struct User {
                string username;
                string email;
                string unverifiedEmail;
                string password;
        }

        struct UserCreate {
                string username;
                string email;

                void applyTo(ref User user) {
                        user.username = this.username;
                        user.unverifiedEmail = this.email;
                }
        }

        struct UserChangePassword {
                string password;

                void applyTo(ref User user) {
                        user.password = this.password;
                }
        }

        // Not usable for structs
        interface Event {
                void applyTo(T)(ref T entity);
        }

        void main() {
                // How can I create an array with mixed structs?
                Event[] events;

                events ~= UserCreate("hej", "h...@example.com");
                events ~= UserChangePassword("hased1234");

                User user;
                foreach (event; events) {
                        event.applyTo(user);
                }

                writeln(user);
        }

Reply via email to