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
xi := []int{2,3,4}// append the number 5xi = append(xi, 5)fmt.Println(xi)// [2 3 4 5]// prepend the number 1xi = 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
...
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
import
_
A simple example:
Sources// +build toolspackage toolsimport (_ "github.com/path/to/some/tool")
Additional References
Links
- Go cheatsheet
- Go Playground
- Go Play Space - an alternative to Go playground with syntax highlighting and inline documentation.
Comparisons
Logging frameworks
This article compares logrus with zap. https://www.libhunt.com/compare-logrus-vs-zap