development

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 […]

Read more
development

Time Complexity of a Memoized Algorithm

The memoization eliminated duplicate calls to a function. A memoized implementation of Fibonacci code is as follows: package complexity import “fmt” var mem map[int]int func fibo(count int) int { if count == 0 || count == 1 { return count } if mem[count] != -1 { return mem[count] } s := fibo(count-1) + fibo(count-2) mem[count] […]

Read more
development

Summary: How to Write Go Code

Summary: How to Write Go Code The code organization follows repository -> module -> packages. Use go mod init and initialize module root as desired e.g. example.com/user/hello The Go binary goes to the path set in GOBIN All imported modules are stored in GOPATH/pkg/mod subdirectory The command go clean -modcache cleans downloaded packages. Reference https://golang.org/doc/code.html […]

Read more
development

Go, gorm, nested JSON and associations

Go, gorm, nested JSON and associations gorm provides a clean way to store a nested JSON with the relation of associations among tables. The following code creates a DB with three levels of nesting. package main import ( “encoding/json” “fmt” “github.com/jinzhu/gorm” _ “github.com/lib/pq” ) const ( host = “localhost” port = 5432 user = “postgres” […]

Read more
development

go tool: no such tool “compile”

I started facing go tool: no such tool “compile” error after installing a local build of go. The golang source was in /usr/local $ cd /usr/local $ ls total 41240 drwxr-xr-x@ 19 root wheel 608B Oct 18 19:35 go drwxr-xr-x 16 root wheel 512B Oct 18 19:35 . -rw-r–r–@ 1 root wheel 20M Oct 18 […]

Read more