Factory Method

This lesson tells what a factory is and how to make and use a factory. In the later part, we revisit some important functions.

A factory of structs

Go doesn’t support constructors as in OO-languages, but constructor-like factory functions are easy to implement. Often, a factory is defined for the type for convenience. By convention, its name starts with new or New. Suppose we define a File struct type:

type File struct {
  fd int // file descriptor number
  name string // filename
}

Then, the factory, which returns a pointer to the struct type, would be:

func NewFile(fd int, name string) *File {
  if fd < 0 {
    return nil
  }
  return &File{fd, name}
}

Often a Go constructor can be written succinctly using initializers within the factory function. An example of calling it:

f := NewFile(10, "./test.txt")

If File is defined as a struct type, the expressions new(File) and &File{} are equivalent. Compare this with the clumsy initializations in most OO languages:

File f = new File( ...)

In general, we say that the factory instantiates an object of the defined type, just like in class-based OO languages. How to force using the factory method? By applying the Visibility rule, we can force the use of the factory method and forbid using new, effectively making our type private as it is called in OO-languages.

package matrix
type matrix struct {
  ...
}
function NewMatrix(params) *matrix {
  m := new(matrix)
  // m is initialized

  return m
}

Because of the m of matrix, we need to use the factory method in another package:

package main
import "matrix"
...
wrong := new(matrix.matrix) // will NOT compile (the struct matrix can't be used directly)
right := matrix.NewMatrix(...) // the ONLY way to instantiate a matrix

new() and make() revisited for maps and struct

The difference between these two built-in functions was clearly defined in Chapter 5 with an example of slices. By now, we have seen two of the three types for which make() can be used: slices and maps. The 3rd make type is channels, which we will discuss in Chapter 12.

To illustrate the difference in behavior for maps and possible errors, experiment with the following program:

Get hands-on with 1400+ tech skills courses.