MDGSF Software Engineer

[GO] map for value

2018-01-16
GO

package main

import (
    "fmt"
)

type student struct {
    Name string
    Age  int
}

func main() {

    m := pase_map()

    for k, v := range m {
        fmt.Printf("key = %s,value =%v\n", k, v)
    }

}

func pase_map() map[string]*student {

    m := make(map[string]*student)

    stu := []student{
        {"joy", 12}, {"lei", 14}, {"jian", 18},
    }

    for _, v := range stu {

        m[v.Name] = &v
    }
    return m
}
$ go run test.go
key = joy,value =&{jian 18}
key = lei,value =&{jian 18}
key = jian,value =&{jian 18}

说明 v 一直都是同一个变量。

修正

package main

import (
    "fmt"
)

type student struct {
    Name string
    Age  int
}

func main() {

    m := pase_map()

    for k, v := range m {
        fmt.Printf("key = %s,value =%v\n", k, v)
    }

}

func pase_map() map[string]*student {

    m := make(map[string]*student)

    stu := []student{
        {"joy", 12}, {"lei", 14}, {"jian", 18},
    }

    for k, v := range stu {

        m[v.Name] = &stu[k]
    }
    return m
}
$ go run test.go
key = joy,value =&{joy 12}
key = lei,value =&{lei 14}
key = jian,value =&{jian 18}

weixingongzhonghao

下一篇 [GO] select

Comments

Content