心美,一切皆美

人生的弓,拉得太满人会疲惫,拉得不满人会掉队,我们要学会张弛有度

[golang]map的value赋值和遍历赋值

1、=========map的value赋值=========

package main

import "fmt"

type Student struct {
	Name string
}

var list map[string] Student

//map的Value赋值
func main()  {

	list = make(map[string] Student)

	student := Student{"action"}

	list["student"] = student
	//list["student"].Name = "xd" //错误 cannot assign to struct field list["student"].Name in map

	tempStudent := list["student"]
	tempStudent.Name = "xd"
	list["student"] = tempStudent

	fmt.Println(list["student"])


}

2、=========map的遍历赋值=========

package main

import "fmt"

type People struct {
	Name string
	Age int
}


//map的遍历赋值
func main()  {
	//定义map
	list := make(map[string] *People)

	//定义student数组
	peoples := []People{
		{Name: "zhou", Age: 24},
		{Name: "li", Age: 23},
		{Name: "xing", Age: 22},
	}

	//遍历结构体数组,依次赋值给map
	for i:=0;i<len(peoples);i++{
		list[peoples[i].Name] = &peoples[i]
	}

	//打印map
	for k,v := range list{
		fmt.Println(k,"=>",v.Name)
	}

}

分类:  

程序积累

 / 

标签:  


golang




map

 / 
浏览量:  4

2022-7-5 15:49 Tuesday


点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注