Go struct类型的map结构体成员不能修改的问题

原问地址

https://studygolang.com/articles/31024

修改方法说明

方法1

package test1

import (
    "fmt"
    "testing"
)

type Person struct{
    Name string
    Age int
    Gender string
}

func TestMap1(t *testing.T){

    m1 := map[uint]Person{
        1: {"whw", 12, "male"},
        2: {"naruto", 22, "male"},
    }

    fmt.Println("m1: ", m1)
    // TODO 传入一个临时结构体 修改map中的结构体然后再赋值即可
    tempObj := m1[1]
    tempObj.Name = "www"
    tempObj.Age = 21
    tempObj.Gender = "MALE"
    m1[1] = tempObj

    fmt.Println("m1: ", m1)
}

方法2

package test1

import (
    "fmt"
    "testing"
)

type Person struct{
    Name string
    Age int
    Gender string
}

func TestMap2(t *testing.T){
    // 定义阶段使用结构体指针
    m2 := map[uint]*Person{
        3: &{"sasuke", 22, "male"},
        4: &{"sakurua", 21, "female"},
    }

    fmt.Println("m2: ", m2)
    fmt.Println("name: ", m2[3].Name)

    
    m2[3].Name = "SASUKE"
    m2[3].Age = 25
    m2[3].Gender = "MALE"

    fmt.Println("m2: ", m2)
    fmt.Println("name: ", m2[3].Name)

}

~~~

 

posted on 2021-03-06 14:11  江湖乄夜雨  阅读(326)  评论(0编辑  收藏  举报