package main
import (
"fmt"
)
func main() {
//多维map的声明与实现
//方法1:初始化一个空的多维映射
mainMapA := map[string]map[string]string{}
subMapA := map[string]string{"A_Key_1": "A_SubValue_1", "A_key_2": "A_SubValue_2"}
mainMapA["MapA"] = subMapA
fmt.Println("\nMultityMapA")
fmt.Println("mainMapA[\"MapA\"]", mainMapA["MapA"])
//输出:mainMapA["MapA"] map[A_Key_1:A_SubValue_1 A_key_2:A_SubValue_2]
fmt.Println("mainMapA", mainMapA)
//输出:mainMapA map[MapA:map[A_Key_1:A_SubValue_1 A_key_2:A_SubValue_2]]
for keyA, valA := range mainMapA {
fmt.Printf("keyA:%s val:%s\n", keyA, valA)
//输出:keyA:MapA val:map[A_Key_1:A_SubValue_1 A_key_2:A_SubValue_2]
for subKeyA, subValA := range valA {
fmt.Printf("mapName=%s Key=%s Value=%s\n", keyA, subKeyA, subValA)
//mapName=MapA Key=A_Key_1 Value=A_SubValue_1
//mapName=MapA Key=A_key_2 Value=A_SubValue_2
}
}
//方法2 使用make声明一个多维映射(等同一般声明)
//var mainMap map[string]map[string]string
mainMap := make(map[string]map[string]string)
subMap := make(map[string]string)
subMap["key_1"] = "SubValue_1"
subMap["key_2"] = "SubValue_2"
mainMap["Map"] = subMap
fmt.Println("\nMultityMap")
for key, val := range mainMap {
for subkey, subval := range val {
fmt.Printf("mapName=%s Key=%s Value=%s\n", key, subkey, subval)
}
}
//方法3 使用interface初始化一个一维映射
//关键点:interface{}可以代表任意类型
//原理知识点interface{}就是一个空接口,所有类型都实现了这个接口,所以可以代表所有类型
//mainMapC :=make(map[string]interface{})
mainMapC := map[string]interface{}{}
subMapC := make(map[string]string)
subMapC["C_key_1"] = "C_SubValue_1"
subMapC["C_key_2"] = "C_SubValue_2"
mainMapC["MapC"] = subMapC
fmt.Println("\nMutityMpc")
for keyC, valC := range mainMapC {
fmt.Println("keyC", keyC)
fmt.Println("valC", valC)
//此处必须实例化接口类型,即*.(map[string]string)
//实例化:是将一个抽象的概念类,具体到该类的实物过程
//c := valC.(map[string]string)
for subKeyC, subValC := range valC.(map[string]string) {
fmt.Printf("mapName=%s Key=%s Value=%s\n", keyC, subKeyC, subValC)
}
}
//附加方法值为任何类型:
mainMapD := map[string]map[string]interface{}{}
subMapD := make(map[string]interface{})
subMapD["D_key_1"] = "C_SubValue_1"
subMapD["D_key_2"] = 111
mainMapD["MapD"] = subMapD
fmt.Println("\nMutityMpD")
for keyD, valD := range mainMapD {
fmt.Println("keyD", keyD)
fmt.Println("valD", valD)
for subKeyD, subvalD := range valD {
fmt.Printf("mapName=%s Key=%s Value=%s\n", keyD, subKeyD, subvalD)
}
}
//附加方法
mainMapE := map[string]interface{}{}
subMapE := make(map[string]interface{})
subMapE["C_key_1"] = "C_SubValue_1"
subMapE["C_key_2"] = 222
mainMapE["MapC"] = subMapE
fmt.Println("\nMutityMpE")
for keyE, valE := range mainMapE {
fmt.Println("keyC", keyE)
fmt.Println("valC", valE)
//此处必须实例化接口类型,即*.(map[string]string)
//实例化:是将一个抽象的概念类,具体到该类的实物过程
//c := valC.(map[string]string)
for subKeyE, subValE := range valE.(map[string]interface{}) {
fmt.Printf("mapName=%s Key=%s Value=%s\n", keyE, subKeyE, subValE)
}
}
}