Michael Krisher
4 min readFeb 9, 2024

--

Rust Structs compared to Ruby classes

Wait, the title says we are comparing Structs and classes, but Ruby has a Struct object, what gives? It does, we’ll get into it.

Photo by Ricardo Gomez Angel on Unsplash

If you’ve been following along, we haven’t gotten into code structure yet. We’ve scratched the surface of classes and objects in the last post about Enums but in this post, we’re going to lay out the foundation of “classes” in Rust compared to Ruby.

In the Enum post, we created a User class in Ruby with some constants that offered us a way to illustrate an equivalent to Rust Enums. The class and output looked like this:

class User
USER_KINDS = [Admin, NonAdmin]
USER_SCORES = [HighScore, LowScore]
USER_CONTACTS = [Electronic, Physical]

attr_accessor :kind, :high_score, :low_score, :contact

def self.admin
USER_KINDS.first
end

def self.nonadmin
USER_KINDS.last
end

def self.high_score(value)
USER_SCORES.first.new(value)
end

def self.low_score(value)
USER_SCORES.last.new(value)
end

def self.contact(email:, text:, city:, state:)
if !email.nil? || !text.nil?
USER_CONTACTS.first.new(email: email, text: text)
elsif !city.nil? || !state.nil?
USER_CONTACTS.last.new(city: city, state: state)
end
end
end

my_user = User.new
my_user.kind = User.admin
my_user.low_score = User.low_score(30)

--

--