Golang can be declared with := while assigning a value to a variable, as well as the scope of the variable. Variables declared in the body of the for loop are scoped from the beginning of the for loop to the end of the curly braces. Give a group of students’ scores for each subject, possibly duplicated, and sum the scores by name.
package main import "fmt" type student struct { Score int Name string } func printMap(m map[string]*student) { for k, v := range m { fmt.Println(k, v) } } func main() { s := make([]student, 0) s = append(s, student{1, "s1"}) s = append(s, student{1, "s2"}) s = append(s, student{2, "s1"}) s = append(s, student{1, "s3"}) m := make(map[string]*student) for idx, v := range s { _, ok := m[v.Name] if ! ok { m[v.Name] = &v } else { m[v.Name].Score += v.Score } fmt.Println(idx) printMap(m) } printMap(m) }Copy the code
The final output of the above code:
s1 &{1 s3}
s2 &{1 s3}
s3 &{1 s3}
Copy the code
Because v is scoped throughout the for loop, it assigns the address of V, which is fixed, and all values are assigned to the same value. Change to the following code:
package main import "fmt" type student struct { Score int Name string } func printMap(m map[string]*student) { for k, v := range m { fmt.Println(k, v) } } func main() { s := make([]student, 0) s = append(s, student{1, "s1"}) s = append(s, student{1, "s2"}) s = append(s, student{2, "s1"}) s = append(s, student{1, "s3"}) m := make(map[string]*student) for idx, v := range s { _, ok := m[v.Name] if ! ok { m[v.Name] = &s[idx] } else { m[v.Name].Score += v.Score } } printMap(m) }Copy the code
Output:
s1 &{3 s1}
s2 &{1 s2}
s3 &{1 s3}
Copy the code