Skip to content

Go associative array

wordpress meta

title: 'Go Associative Array'
date: '2018-08-10T10:46:18-05:00'
status: publish
permalink: /go-associative-array
author: admin
excerpt: ''
type: post
id: 1249
category:
    - go
tag: []
post_format: []

Jotting down my test to implement an associative array similar to as my python test here: https://blog.ls-al.com/python-dict-for-arrays/

In python I used dict and in go I used map.

$ pwd
/home/rrosso/src/examples

$ cat maps.go 
package main
import "fmt"
type rec struct {
    lname, fname string
}

var m map[string]rec

func main() {
    m = make(map[string]rec)
    m["1"] = rec{"Sable", "Sam",}
    m["2"] = rec{"Sable", "Samantha",}
    m["3"] = rec{"Sable", "Stevie",}

    fmt.Println(m)
    fmt.Println(m["2"])
    fmt.Println(m["3"].fname)
    fmt.Println()

        //simpler example no struct
    n := map[string]int{"foo": 1, "bar": 2}
        fmt.Println("map:", n)
    fmt.Println("val:", n["bar"])
}

Output

$ go run maps.go 
map[1:{Sable Sam} 2:{Sable Samantha} 3:{Sable Stevie}]
{Sable Samantha}
Stevie

map: map[foo:1 bar:2]
val: 2