Monday, May 3, 2021

Maps







package main

import "fmt"

func main() {
    colors := map[string]string{
        "red":   "#ff000",
        "green": "#4bf745",
    }

    fmt.Println(colors)
}


Different Ways of defining a Map

package main

import "fmt"

func main() {
    // var colors map[string]string

    colors := make(map[string]string)

    // colors := map[string]string{
    //  "red":   "#ff000",
    //  "green": "#4bf745",
    // }

    fmt.Println(colors)
}


Adding Values

colors["white"] = "#ffffff"


Deleting Values

    colors[10] = "#ffffff"

    delete(colors, 10)

    fmt.Println(colors)


Iterating over Maps


func printMap(c map[string]string) {
    for color, hex := range c {
        fmt.Println("Hex code for", color, "is", hex)
    }
}


Maps vs Structs

No comments:

Post a Comment