Go sorting, an example

I was recently trying to figure out a way to sort entries stored in a map using Golang. And then, I came across the “sort” package. It provides a Sort() function which can used to sort slices and user-defined collections.

func Sort(data Interface)

All you need is to define the functions listed under the Interface type.

Here is an example to demonstrate the same :

package main

import (
        "fmt"
        "sort"
)

type keys []int

/* Definitions for all 'Interface' functions. */
func (k keys) Len() int           { return len(k) }
func (k keys) Less(i, j int) bool { return k[i] < k[j] }
func (k keys) Swap(i, j int)      { k[i], k[j] = k[j], k[i] }

func main() {
        var (
                k keys
                i int
        )

        var varMap = map[int][]string{
                3: []string{"Harry"},
                1: []string{"Tom"},
                2: []string{"Dick"}}

        k = make(keys, 3)

        for key, _ := range varMap {
                k[i] = key
                i++
        }

        sort.Sort(k)

        for i = 0; i < len(k); i++ {
                fmt.Println(k[i], " : ", varMap[k[i]])
        }
}

Output :
>  go run sort.go 
1  :  [Tom]
2  :  [Dick]
3  :  [Harry]

Multiline statements in Golang

As Golang (unlike C, C++, Java, etc.) frees a programmer from using semi-colon ‘;’ to terminate a statement, one might find it problematic to write a miltiline statement in Go.

Lets start with a quote :

“Like C, Go’s formal grammar uses semicolons to terminate statements; unlike C,those semicolons do not appear in the source. Instead the lexer uses a simple rule to insert semicolons automatically as it scans, so the input text is mostly free of them. “

So, based on my experience so far, here is a trick that I would suggest, one can break a line after “an operator”.

        result := a +
                b +
                c
---
func add(a int,
        b int,
        c int) (result int) {
        result = a + b + c
        return
}

Now coming to strings, they can we written in two ways.

1) Interpreted string literal :

        str := "Lorem ipsum dolor sit amet, consectetur adipisicing" +
               " elit, sed do eiusmod tempor\nincididunt ut labore " +
               " et dolore magna aliqua. Ut enim ad minim veniam," +
               " quis nostrud\nexercitation ullamco laboris ..."

2) Raw string literal :
For multiline strings, back quote ‘`’ can also be used with a couple of restrictions :
a) Any character is legal except back quote.
b) Escape sequences won’t be interpreted.

        str := `Lorem ipsum dolor sit amet, consectetur adipisicing 
                elit, sed do eiusmod tempor incididunt ut labore et
                dolore magna aliqua. Ut enim ad minim veniam, quis
                nostrud exercitation ullamco laboris ...`

go go go…