Tag: development

How to Check nil Interface in Golang?

Never check an interface for nil. Try the following code: type user interface{} type staff struct{} func compareNil() { var generic user generic = (*staff)(nil) fmt.Printf(“value=%v type=%T (generic==nil)=%v\n”, generic, generic, generic == nil) generic = (nil) fmt.Printf(“value=%v type=%T (generic==nil)=%v\n”, generic, generic, generic == nil) } go playground: https://play.golang.org/p/7J9DeIjgNia Output value=<nil> type=*main.staff (generic==nil)=false value=<nil> type=<nil> (generic==nil)=true…

Golang: Careful with Named Return Parameters in Function

package main import ( “fmt” ) func riskyParams() (num int, flag bool) { if num == 0 { // Named parameters have default values in the scope flag = true } return // Beware of such return. You might return something unintended } func main() { num, flag := riskyParams() fmt.Printf(“num=%d flag=%v\n”, num, flag) }…

The Best Git Commands for Dev

The most common part is: The basic cycle git pull master to get up to date git checkout -b myname-feature to get a branch of your own git add <files> that you changed/created git add . to add everything in the current directory git add -u to add all existing files in the repo git…

Why be careful with defer in Golang

When does defer function executes? The standard answer is: defer runs a function before the enclosing function returns. It is a wrong explanation. The defer executes as follows: The enclosing function has processed returned values and stored them in registers All defer functions run in a LIFO order of definition. If the return parameters are…

How to Fix File is not `gofumpt`-ed (gofumpt) error

gofumpt is a stricter version of gofmt. The lint tool finds more errors and reports. One such error is that File is not gofumpt-ed. The solution to the problem is as follows: Please install gofumpt The easiest solution is to run gofumpt on the troubled files. gofumpt -w <fileame> Written with StackEdit.

Interface Quirks in Golang

An interface defines a set of methods. A struct type implements these methods and qualifies the object type as an interface type. However, how the struct implements the interface? There are two ways: As a pointer handler As a value handler Implementation with a struct value handler package main import ( “fmt” ) type Dummy…

go-kit: Sample Code for Function to Log

go-kit: Sample Code for Function to Log func getLogger() log.Logger { var logger log.Logger logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr)) logger = log.With(logger, “instance_id”, 123) return logger } The above function is easily usable in a go-kit project to log JSON style data. func myfun() { mylogger := getLogger() mylogger.Log(“a key”, “a value”) } Reference https://github.com/go-kit/kit/tree/master/log Written with…