10 Go Tips to Boost Productivity

Beck Moulton
6 min read3 days ago

Recently, Phuong Le boss summarized some useful Go tips for daily development of Go projects.

After reading it, I feel that it has certain learning value for colleagues who have just started learning Go. You can choose good ones to learn and apply them to your own projects. The following content is shared with everyone.

While developing Go production projects, I found myself frequently rewriting code and using certain techniques, only realizing this later when I looked back on my work.

Here are some useful code snippets selected from the summary experience, hoping to be helpful to everyone.

1. Timing skills

If you are interested in tracking the execution time of functions or need to use it when troubleshooting.

You can use the deferkeyword in Go to implement a very simple and efficient trick with just one line of code.

You only need one TrackTime function:

func TrackTime(pre time.Time) time.Duration {
elapsed := time.Since(pre)
fmt.Println("elapsed:", elapsed)

return elapsed
}

func TestTrackTime(t *testing.T) {
defer TrackTime(time.Now()) // <-- this

time.Sleep(500 * time.Millisecond)
}

// elapsed: 501.11125ms

1.5 Two-Phase Deferred

The power of Go’s defer lies not only in cleaning up after the task is completed, but also in preparing for the task.

--

--

Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton