Factory Method
Explore how to implement factory methods in Go to create and initialize structs effectively. Learn the difference between new and make functions, their appropriate use with structs and maps, and how to enforce factory patterns through visibility rules for safer memory management in Go programs.
We'll cover the following...
We'll cover the following...
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, ...