Introduction to structs

In D, like in all modern languages, you can define your own types.

These are the four custom types of… types you can create:

  • struct
  • class
  • union
  • enum

This tutorial is an introduction to structs.

structs are types that are defined by programmers and represent records. For example, you could have a Point struct that has two data members: x and y.

Let’s see a simple example.
Suppose we are making an application with jokes.
We could define a type, Joke, to hold the required data of a joke:

Alright, seems easy. But a jokes application without jokes sucks… So let’s add some!

Note that we are able to construct the jokes with the syntax: Joke(id, text, category).

Better. The users might actually laugh now.
But there’s still a small problem. The data members are public, which means a reckless programmer might accidentally mutate them. We don’t want this to ever happen, so let’s define some getters.

What we have done is to make id, text and category const private member variables, and provided property getters to access them.

We could have made the variables const without providing property getters, but as good citizens of encapsulation, we should not expose the public fields.

Here is the full source code:

And the output:

Category: Chuck Norris
“Some magicians can walk on water. Chuck Norris can swim through land.”

Category: Food
“Why don’t the French eat snails? They don’t like fast food.”

Category: Animals
“Why did the dinosaur cross the road? Chickens hadn’t evolved yet”

Want more? Check out Humorista: