Initializers and finalizers are specialized methods a type may optionally define. Their use bookends the life of a type's objects. Initializers help create new objects. Finalizers help destroy them.

Many types don't need initializer or finalizer methods. For those that do, here's how to define them.


Initializer methods offer an alternative to type constructors for creating new values of some type. Type constructors have the limitation that they can only specify initial values for public fields of a new object. Initializers offer more flexibility, as they can use any sort of logic for initializing a new object's fields, even private fields.

Initializers are useful when the use of a type constructor would be:

Here is a simple initializer:

fn init(self &new)
  *self = Self[x: 1., y: 1., z: 1.]

An initializer is a method, but it has a few differences from typical methods:

The following code invokes the initializer defined above:

imm gcref = &gc mut Point()  // x,y,z of the new Point value are 1.0

Clone method

As discussed earlier, it is not always obvious how to create a faithful copy of some types' values. When this difficulty exists (e.g., a value that contains references to other values), a type may define a clone method whose logic is capable of creating a faithful copy.

A clone method is essentially an initializer whose second parameter is a value or another borrowed reference to the value we want to copy:

fn clone(self &new, from &)
  *self = Self[x: from.x, y: from.y, z: from.z]

Whenever copies are automatically made (e.g., assignment or function calls), the clone method will be used, if specified, to make these copies.

drop Finalizer

When a object is destroyed at the end of its life, its finalizer logic, if defined, is automatically invoked. Only types that acquire a dependent relationship with other system object(s) need to define a finalizer. The finalizer releases, gives back, or safely breaks all such dependencies (e.g., closing file/network handles, de-subscribing to services, etc.) before the value's memory is reclaimed.

Here's a finalizer:

fn drop(self &uni)

Key to a finalizer definition: