Methods in enums

Alexandru Ermicioi alexandru.ermicioi at gmail.com
Fri Aug 18 16:10:51 UTC 2023


On Friday, 18 August 2023 at 10:48:45 UTC, sighoya wrote:
> How can I call a method like myEnumInstance.method(arg) when 
> using structs in enums?

Easy-peasy:
```d
import std;

/**
* Note this type and enum ideally should be in separate module, 
to properly hide VoldemortType from rest of the code.
**/
private struct VoldemortType {
     private string message;

     public void say(string post) const {
         writeln(message, " ", post);
     }

     public bool opEquals(Message other) const {
         return other.message == this.message;
     }

     public void sayAlso(Message other, string forSubject) const {
         this.say(forSubject);
         other.say(forSubject);
     }
}

public enum Message : VoldemortType {
     hello = VoldemortType("hello"),
     bye = VoldemortType("bye")
}

void decorate(Message message, string decoration, string subject) 
{
     std.stdio.write(decoration, " ");
     message.say(subject ~ " " ~ decoration);
}

void main()
{
     Message mess = Message.hello;

     mess.say("entity");
     mess.sayAlso(Message.bye, "subject");
     mess.decorate("**", "third-party");

     writeln("Is hello message same as bye?: ", Message.hello == 
Message.bye);
     writeln("Is mess variable a hello message?: ", mess == 
Message.hello);
}
```

As you can see, there is no such cyclicity you've mentioned, and 
using `Message` as parameter to a method or free function (for 
ufcs), doesn't cause any issues.

Still for free functions, you'd have to import them separately 
from enum, which imho is ok, since you can know that it is an 
extension, and not a function part of enum behavior.

Best regards,
Alexandru.


More information about the Digitalmars-d mailing list