Combining Pair with nested map

Problem:

  • Want to read data from CSV file and group it based on this combination warehouse[item[batch, qty]]
  • [Batch, Qty] pair should be inserted in sequence

Approach:

  • I thought best way to make it is to use a combination of map and pair/tuple

Code:

package main

import "fmt"

type Pair struct {
	Key   string
	Value float64
}

func main() {
	fmt.Println("Hello, δΈ–η•Œ")
	var inventory = map[string]map[string][]Pair{} //warehouse[item[batch, qty]]
	fmt.Printf("%T\n", inventory)
	inventory["DMM"] = map[string][]Pair{}  // map[string]map[string][]main.Pair
	fmt.Printf("%T\n", inventory["DMM"])
	inventory["DMM"]["Helmet"] = []Pair{}
	fmt.Printf("%T = %v\n", inventory["DMM"]["Helmet"])
	
	inventory["DMM"]["Helmet"] = append(inventory["DMM"]["Helmet"], Pair{"Jan", 10}) 
     fmt.Printf("%T = %v\n", inventory["DMM"]["Helmet"][0])
}

Code error

Hello, δΈ–η•Œ
map[string]map[string][]main.Pair
map[string][]main.Pair
[]main.Pair = %!v(MISSING)
main.Pair = %!v(MISSING)

Notes

  • It looks I was able to enter the warehouse and item combination correctly, but something not correct for entering/inserting/adding/appending the Pair to this combination!

Fixing the usage of fmt.Printf helps:

package main

import "fmt"

type Pair struct {
	Key   string
	Value float64
}

func main() {
	var inventory = map[string]map[string][]Pair{} //warehouse[item[batch, qty]]
	inventory["DMM"] = map[string][]Pair{}         // map[string]map[string][]main.Pair
	inventory["DMM"]["Helmet"] = []Pair{}
	inventory["DMM"]["Helmet"] = append(inventory["DMM"]["Helmet"], Pair{"Jan", 10})

	fmt.Printf("inventory[\"DMM\"][\"Helmet\"][0]: %T = %v\n", inventory["DMM"]["Helmet"][0], inventory["DMM"]["Helmet"][0])
}

Output:

inventory["DMM"]["Helmet"][0]: main.Pair = {Jan 10}

https://play.golang.org/p/xtxzPQdWuo8

1 Like

Deeply appreciated

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.