Maps in Golang

How to iterate over a Map using for loop in Go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package main
 
import "fmt"
 
func main() {
    fmt.Println("Welcome to goLang Maps")
 
    languages := make(map[string]string)
    languages["JS"] = "Javascript"
    languages["JA"] = "Java"
    languages["PY"] = "Python"
 
    for key, element := range languages {
        fmt.Println("Key:", key, "=>", "Element:", element)
    }
 
}

How to write map values into a file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package main
 
import (
    "fmt"
    "log"
    "os"
)
 
func main() {
    fmt.Println("Welcome to goLang Maps")
 
    languages := make(map[string]string)
    languages["JS"] = "Javascript"
    languages["JA"] = "Java"
    languages["PY"] = "Python"
 
    f, err := os.Create("test.txt")
    if err != nil {
        fmt.Println(err)
        return
    }
 
    // remember to close the file
    defer f.Close()
 
    for key, element := range languages {
        fmt.Println("Key:", key, "=>", "Element:", element)
        _, err := f.WriteString(key + "," + element + "\n")
        if err != nil {
            log.Fatal(err)
        }
    }
 
}

How to read line by line from a file and create map values

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package main
 
import (
    "bufio"
    "fmt"
    "log"
    "os"
    "strings"
)
 
func main() {
    fmt.Println("Welcome to goLang Maps")
 
    languages := make(map[string]string)
 
    file, err := os.Open("test.txt")
    if err != nil {
        log.Fatal(err)
    }
 
    // remember to close the file
    defer file.Close()
 
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        keyvalue := scanner.Text()
        keypairs := strings.Split(keyvalue, ",")
        languages[keypairs[0]] = keypairs[1]
    }
 
    fmt.Println(languages)
 
    if err := scanner.Err(); err != nil {
        log.Fatal(err)
    }
 
}