go的map类型的情况

package main

import (
"fmt"
"math/rand"
"time"
)

func modify(a map[string]int) {
a["modify001"] = 1000
}

// map是引用类型,复制和赋值都是源引用,跟着变化
func testMap() {
var a map[string]int
a = make(map[string]int, 16)
fmt.Printf("01 a=%v len(a)=%d \n", a,len(a)) // cap(a) invalid argument a (type map[string]int) for cap
a["stu01"] = 11
a["stu02"] = 12
a["stu03"] = 13
fmt.Printf("02 a=%#v len(a)=%d \n", a,len(a))

b := a
fmt.Printf("03 a=%v\n", a)
fmt.Printf("04 b=%v\n", b)
b["stu03"] = 103
fmt.Printf("05 a=%v\n", a)
fmt.Printf("06 b=%v\n", b)

modify(a)
fmt.Printf("07 a=%v len(a)=%d \n", a,len(a))
fmt.Printf("08 b=%v\n", b)

}

func testMap1() {
rand.Seed(time.Now().UnixNano())
var a map[string]int = make(map[string]int, 10)
for i := 0; i < 5; i++ {
key := fmt.Sprintf("stu%d", i)
value := rand.Intn(1000)
a[key] = value
}
fmt.Printf("delete before a=%#v len(a)=%d \n", a,len(a))
delete(a, "stu3")
fmt.Printf("delete after a=%#v len(a)=%d \n", a,len(a))

for key, value := range a {
	fmt.Printf("map a[%s]=%d\n", key, value)
}

}

func testMap2(){
var a map[string]int
a = make(map[string]int,16)
a["stu01"] = 11
a["stu02"] = 12
a["stu03"] = 13
fmt.Printf("testMap2 #v a=%#v\n",a)
fmt.Printf("testMap2 v a=%v\n",a)

var result int
result = a["stu04"]  // 如果map中没有"stu04"则返回 int:0 string:"",float:0.0
fmt.Printf("result:%d\n",result)

var ok bool
var result1 int
var key string="stu031"
result1,ok = a[key]
if ok == false {
	fmt.Printf("key %s is not exist \n",key)
}else{
	fmt.Printf("key %s is %d\n",key,result1)
}

}

func main() {
testMap()
//testMap1()
//testMap2()
}

posted @ 2022-03-06 00:01  ty1539  阅读(33)  评论(0编辑  收藏  举报