Member-only story
If you are coming from Ruby, you may not be completely familiar. More than likely you’ve heard of Enums in the context of database validation. Typically, we’d use Enums while deciding if a given value is an acceptable value for a database column. In Ruby, a lot of times this is done using a list of acceptable values.
In our project files from the previous posts, we’ll create types of users. The types will be used to illustrate the use of Rust Enums.
In Ruby, we could do something like this:
class Admin
NAME = "Administrator"
end
class NonAdmin
NAME = "Application User"
end
class User
USER_KINDS = [Admin, NonAdmin]
attr_accessor :kind
def self.admin
USER_KINDS.first
end
def self.nonadmin
USER_KINDS.last
end
end
my_user = User.new
my_user.kind = User.admin # we could have used USER_KINDS.first
puts my_user.kind # prints out Admin
puts my_user.kind::NAME # prints out Administrator
We could add validation to this to make sure that User#kind is only ever set to a value included in USER_KINDS constant, but let’s see what the equivalent is in…