Home About Contact
Go , Groovy

Golang, マップの使用例

ポケモンのタイプ別にポケモンリストを用意する例。 Golang の マップでそれを実装方法の備忘録。

package main

import "fmt"

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

	keyWater := "water"
	db[keyWater] = []string{}
	db[keyWater] = append(db[keyWater], "Squirtle")
	db[keyWater] = append(db[keyWater], "Psyduck")

	keyIce := "ice"
	db[keyIce] = []string{}
	db[keyIce] = append(db[keyIce], "Regice")
	db[keyIce] = append(db[keyIce], "Snover")

	keyFire := "fire"
	db[keyFire] = []string{}
	db[keyFire] = append(db[keyFire], "Charamander")
	db[keyFire] = append(db[keyFire], "Charizard")
	db[keyFire] = append(db[keyFire], "Torchic")

	for k, v := range db {
		fmt.Println(fmt.Sprintf("- %s type: ", k))
		for _, name := range v {
			fmt.Println(fmt.Sprintf("  - %s", name))
		}
	}
}

ビルドして実行すると:

- water type: 
  - Squirtle
  - Psyduck
- ice type: 
  - Regice
  - Snover
- fire type: 
  - Charamander
  - Charizard
  - Torchic

Groovy で書き直すと以下のとおり:

def db = [:]

def keyWater = 'water'
db.put(keyWater, [])
db[keyWater].add('Squirtle')
db[keyWater].add('Psyduck')

def keyIce = 'ice'
db.put(keyIce, [])
db[keyIce].add('Regice')
db[keyIce].add('Snover')

def keyFire = 'fire'
db.put(keyFire, [])
db[keyFire].add('Charamander')
db[keyFire].add('Charizard')
db[keyFire].add('Torchic')

db.each { k,v->
    println "- $k type:"
    v.each { name->
        println "  - $name"
    }
}