GO – Types (part 2)

Range

Range iterates over a slice. Range returns two values while iterating over a slice. First is the index of the element and second a copy of the element at that index.

package main

import "fmt"

var t = []int{1, 3, 6, 9, 12, 15, 18, 21}

func main() {
	
	for i,v := range t {
	   fmt.Printf("%d => %d\n", i, v)
	}
}
  • Index or Value can be skipped by assigning it to _.
  • If only indexes are required, the “value” can be dropped entirely.
func main() {
	
	fmt.Printf("Values:\n")
	for _,v := range t {
	   fmt.Printf("%d, ", v)
	}
	
    fmt.Printf("\nIndex:\n")
    for i:= range t {
	   fmt.Printf("%d, ", i)
	}

}

Map

Map is nothing but a key-value pair. ‘Make’ function can be used to initialize a map. Zero value of a map is ‘Nil‘. Keys cannot be added to a ‘nil’ map.

package main

import "fmt"

var Emp map[string]int

func main() {
   Emp = make(map[string]int)
   Emp["John"] = 34
   Emp["Jeff"] = 20
   fmt.Println(Emp)
   fmt.Println(Emp["John"])
}

Map Literals:

package main

import "fmt"

type address struct {
  street, city string
  }

var Emp = map[string]address{
	"John": address{"abc street","London"},
	"Jeff": {"def street","Boston"},
}

The top-level type name (address in this case) can be omitted as well.

Mutating Maps

m = make(map[string]int)

  • Insert/Update” m["Mary"] = 58
  • Retrieve an element: fmt.Println(m["Mary"])
  • delete: delete(m,"Mary")
  • Check if a key is present: val, present := m["Jerry"] If the key is present, val will return the value and present will be True. If the key is not present, val will be 0 and present will be False.

Implementing Word Count

A small exercise to create a Map which will contain the count of each letter in a given word:

package main

import (
	"strings"
	"fmt"
)

func WordCount(s string) map[string]int {
    split := strings.Fields(s)
	wc := make(map[string]int)
	for i:=0;i<len(split);i++ {
	   wc[split[i]] = len(split[i])
	}
	return wc
}

func main() {
	fmt.Println(WordCount("I am learning Go!"))
}

Function values

In GO, Functions can also be passed around, similar to values.

package main

import (
  "fmt"
  "math"
)

func compute(fn func(float64, float64) float64) float64 {
   return fn(4,3)
}

func main() {
   sqrt := func(x,y float64) float64 {
       return math.Sqrt(x*x + y*y)
    }
   fmt.Println(compute(math.Pow))
   fmt.Println(compute(sqrt))
}

Function Closures

Closure is a function that references values from outside its body.

package main

import (
 "fmt"
)

func closure() func(int) int {
 sum := 0
 return func(x int) int {
 sum +=x
 return sum
 }
}
func main() {
 sum1,sum2 := closure(), closure()
 for i:=0;i<10;i++ {
 fmt.Println(sum1(i),sum2(-1*i))
 }
}

Previous post: GO – Types (part 1)

Next Post: Go – Methods and Interfaces

3 comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s