Golang: Map, Hashes, Dictionary


Golang Maps are similar to what other language call ‘dictionaries’ or ‘hashes’.

 

package main

import "fmt"

var names = map[string]int{"Katrina": 10, "Evan": 11, "Neil": 12}

func main() {
    //  fmt.Printf("%#v", names)

    for x, _ := range names {
        fmt.Println(x)
    }
    // Output:
    // Katrina
    // Evan
    // Neil

    for _, name := range names {
        fmt.Println(name)
    }
    // Output:
    // 10
    // 11
    // 12

    for x, name := range names {
        fmt.Printf("%s : %d \n", x, name)
    }
    // Output
    // Katrina : 10
    // Evan : 11
    // Neil : 12

}

Add / Append new data to a map


package main

import "fmt"

func main() {
	names := make(map[string]int)
	//	fmt.Printf("%#v", names)

	names["jhony"] = 1
	names["beta"] = 2

	for x, name := range names {
		fmt.Printf("%s : %d \n", x, name)
	}

}

Collection of objects


package main

import "fmt"

type Person struct {
	name, address string
}

func main() {
	jelemas := make(map[string]Person)

	jelemas["Yoesoff"] = Person{"yusuf", "Jl. Wakwau no.09"}
	jelemas["Yuka"] = Person{"gokana", "Jl. Wakwau no.90"}
	jelemas["Mumun"] = Person{"pocong", "Jl. Wakwau no.99"}

	//	fmt.Printf("%#v", names)
	for x, wong := range jelemas {
		fmt.Printf("%s : %s (%s) \n", x, wong.name, wong.address)
	}

	// Output
	// Yuka : gokana (Jl. Wakwau no.90)
	// Mumun : pocong (Jl. Wakwau no.99)
	// Yoesoff : yusuf (Jl. Wakwau no.09) 

}

Remove / Delete item from map


package main

import "fmt"

type Person struct {
	name, address string
}

func main() {
	jelemas := make(map[string]Person)

	jelemas["Yoesoff"] = Person{"yusuf", "Jl. Wakwau no.09"}
	jelemas["Yuka"] = Person{"gokana", "Jl. Wakwau no.90"}
	jelemas["Mumun"] = Person{"pocong", "Jl. Wakwau no.99"}

	//	fmt.Printf("%#v", names)
	for x, wong := range jelemas {
		fmt.Printf("%s : %s (%s) \n", x, wong.name, wong.address)
	}

	// Output
	// Yuka : gokana (Jl. Wakwau no.90)
	// Mumun : pocong (Jl. Wakwau no.99)
	// Yoesoff : yusuf (Jl. Wakwau no.09)

	delete(jelemas, "Mumun")

	fmt.Println("Delete Mumun (Because he is scary)")
	for x, wong := range jelemas {
		fmt.Printf("%s : %s (%s) \n", x, wong.name, wong.address)
	}

	// Output
	// Delete Mumun (Because he is scary)
	// Yoesoff : yusuf (Jl. Wakwau no.09)
	// Yuka : gokana (Jl. Wakwau no.90)

}

Check Element existence in a map


	// Check Element
	_, ok := jelemas["Yuka"]

	fmt.Println(ok)

	_, ok = jelemas["Mumun"]

	fmt.Println(ok)

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s