10

Constructors deconstructed [best practice]

 3 years ago
source link: https://yourbasic.org/golang/constructor-best-practice/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Constructors deconstructed [best practice]

yourbasic.org/golang

Go doesn't have explicit constructors. The idiomatic way to set up new data structures is to use proper zero values coupled with factory functions.

factory-conveyor-belt.jpg

Zero value

Try to make the default zero value useful and document its behavior. Sometimes this is all that’s needed.

// A StopWatch is a simple clock utility.
// Its zero value is an idle clock with 0 total time.
type StopWatch struct {
    start   time.Time
    total   time.Duration
    running bool
}

var clock StopWatch // Ready to use, no initialization needed.
  • StopWatch takes advantage of the useful zero values of time.Time, time.Duration and bool.
  • In turn, users of StopWatch can benefit from its useful zero value.

Factory

If the zero value doesn’t suffice, use factory functions named NewFoo or just New.

scanner := bufio.NewScanner(os.Stdin)
err := errors.New("Houston, we have a problem")

Share:             


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK