destroy() Example

Let’s look at an example that demonstrates the use of the destroy() function.

We'll cover the following

Example

We had designed an XmlElement struct in the constructor and other special functions chapter. We were using that struct for printing XML elements in the format value. Printing the closing tag was the responsibility of the destructor:

struct XmlElement { 
    // ...
    ~this() {
        writeln(indentation, "</", name, '>'); 
    }
}

The following output was produced by a program that used the XmlElement struct. This time, we are replacing the word “class” with “course” to avoid confusing it with the class keyword:

<courses>
  <course0>
    <grade>
      72 
    </grade>   ← the closing tags appear on correct lines
    <grade> 
      97 
    </grade>   ←
    <grade>
      90 
    </grade>   ←
  </course0>   ←
  <course1>
    <grade> 
      77
    </grade>   ←
    <grade>
      87
    </grade>   ←
    <grade>
      56
   </grade>    ←
  </course1>   ←
</courses>     ←

The previous output happens to be correct because XmlElement is a struct. The desired output is achieved simply by placing the objects in the appropriate scopes:

Get hands-on with 1200+ tech skills courses.