...

/

Factory Method

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 ...