Skip to main contentEric N. Garcia

Go

This page is a collection of tips and tricks I’ve come to learn about the Go programming language.

Slice: Append & Prepend

To append and prepend you would use the same build in

append
go method. The only difference is the oder in which you supply the

xi := []int{2,3,4}
// append the number 5
xi = append(xi, 5)
fmt.Println(xi)
// [2 3 4 5]
// prepend the number 1
xi = append([]int{1}, xi...)

Explanation:

The arguments for append are a slice (first argument), and the 2nd and further arguments are elements you are looking to append to the slice.

So for a standard append you pass it your starting slice, and then any number of elements you wish to append.

For the prepend, you have to pass that starting element in as a slice, you you have to define the slice and type with its literal value. Then for the second argument you unfirl (not sure the proper term here) the slice with

...
. This tells go to pass in the individual values help by that slice rather than the slice itself.

Tools as dependencies

There is a pattern to track tools as dependencies in Go. This is used when you need tools to build your project or generate code for protos, mocks, or any other tools. This pattern is used when those tools are not imported in any files but used by the developer to build the project.

The simplest way to achieve this is to add a tools.go file to the root of your project. This will serve as an individual package. While the name of this package and file are not important, using a descriptive name is always helpful.

In this file you must add the go directive

// +build tools
, and then make sure all tools are listed, in the
import
section. All the tools should be prefixed with
_
, which shows that it is not explicitly imported anywhere else, but is required for the package.

A simple example:

// +build tools
package tools
import (
_ "github.com/path/to/some/tool"
)
Sources

Additional References

Comparisons

Logging frameworks

This article compares logrus with zap. https://www.libhunt.com/compare-logrus-vs-zap