学习golang之刷题(1)

type MS struct {
	Name string
	Cgs  int
}

func b() {
	hashRun := make(map[string]*MS)
	mss := []MS{
		MS{Name: "m", Cgs: 100},
		MS{Name: "m", Cgs: 1},
		MS{Name: "mm", Cgs: 4},
	}
	for _, ms := range mss {
		if h, ok := hashRun[ms.Name]; ok {
			h.Cgs += ms.Cgs
		} else {
			hashRun[ms.Name] = &ms
		}
	}
	for _, ms := range hashRun {
		fmt.Println(ms)
	}
}

func a() {
	hashRun := make(map[string]*MS)
	mss := []MS{
		MS{Name: "m", Cgs: 100},
		MS{Name: "m", Cgs: 1},
	}

	for _, ms := range mss {
		if h, ok := hashRun[ms.Name]; ok {
			h.Cgs += ms.Cgs
		} else {
			hashRun[ms.Name] = &ms
		}
	}

	for _, ms := range hashRun {
		fmt.Println(ms)
	}

}

func c() {
	hashRun := make(map[string]MS)
	mss := []MS{
		MS{Name: "m", Cgs: 100},
		MS{Name: "m", Cgs: 2},
		MS{Name: "mm", Cgs: 4},
	}

	for _, ms := range mss {

		if h, ok := hashRun[ms.Name]; ok {
			MM:=MS{Name: "m", Cgs: ms.Cgs+h.Cgs}
			hashRun[ms.Name]=MM
		} else {
			hashRun[ms.Name] = ms
		}

	}

	for _, ms := range hashRun {
		fmt.Println(ms)
	}

}

func main() {
	a()
	//result:
	//{m 2}
	b()
	//result
	//&{mm 4}
	//&{mm 4}
	c()
	result:
	//{m 102}
	//{mm 4}
}

a方法的h只能有一个,所以永远都是最底的那个,所以输出2
b方法意思有两个key,但都是最新的:{mm 4}

你可能感兴趣的:(go)