Golang Notes

This will encompass things that I find useful and end up looking up later when I haven't written go in a while.

Concepts

A slice is essentially an array in Golang.

Compile binary

go build

Debugging

Start debugger:
dlv debug

Set breakpoint on line 36 in main.go:
break main.go:36

Set breakpoint on line 8 in anotherGoFile.go:
break anotherGoFile.go:8

Debug program with command line arguments (after compiling)
dlv debug -- -a argument -b another_argument

Print contents of the b variable
print b

Restart the debugging process
r

Resources:
https://github.com/derekparker/delve/issues/178
https://www.youtube.com/watch?v=zgLjVD5ZSOc

String Interpolation

var a string = "Hello"
var b string = "World"
c := fmt.Sprintf("%s %s!", a, b)
fmt.Println(c)

Useful Functions

Read an input file from a specified path

func readLines(filePath string) ([]string, error) {
  b, err := ioutil.ReadFile(filePath)
  if err != nil {
    return nil, err
  }

  return RemoveTrailingEmptyStringsInStringArray(strings.Split(string(b), "\n")), nil
}

Remove empty strings trailing in a slice

func RemoveTrailingEmptyStringsInStringArray(sa []string) []string {
  lastNonEmptyStringIndex := len(sa) - 1
  for i := lastNonEmptyStringIndex; i >= 0; i-- {
    if sa[i] == "" {
      lastNonEmptyStringIndex--
    } else {
      break
    }
  }
  return sa[0 : lastNonEmptyStringIndex+1]
}