标签:mpm end 分数 校验 ring false value 根据 长度
package main
import "fmt"
/*
映射(map)是键值对(key-value)数据的集合
根据键key可以快速检索值value
键值的类型可以是任意的,key使用string的时候最多
*/
//创建和访问键值
func main051() {
//定义string为键int为值的映射,用于存储分数
//var scoreMap map[string]int = map[string]int{}
//var scoreMap = map[string]int{}
//scoreMap := map[string]int{}
////没有指定长度,长度为0
scoreMap := make(map[string]int)
////scoreMap := make(map[string]int,2)
//添加键值对数据
scoreMap["张全蛋"] = 59
scoreMap["穆铁柱"] = 63
scoreMap["张半蛋"] = 99
//长度取决于键值对的个数
fmt.Println("映射的长度是", len(scoreMap))//3
fmt.Println(scoreMap)//
//根据键访问值
fmt.Println("张半蛋的成绩是", scoreMap["张半蛋"])//99
fmt.Println("张全蛋的成绩是", scoreMap["张全蛋"])//59
var name = "穆铁柱"
fmt.Println("穆铁柱的成绩是", scoreMap[name])//63
scoreMap["穆铁柱"] = 7
fmt.Println("穆铁柱的成绩是", scoreMap["穆铁柱"])//7
//访问并不存在的键
score := scoreMap["西门志"]
fmt.Println("西门志的成绩是", score)//0
}
//带校验的访问
func main052() {
scoreMap := make(map[string]int)
scoreMap["张全蛋"] = 59
scoreMap["穆铁柱"] = 63
scoreMap["张半蛋"] = 99
//带校验地访问键值
score, ok := scoreMap["穆铁柱"]
fmt.Println(score, ok) //63,true true代表有穆铁柱这个键
score, ok = scoreMap["西门志"]
fmt.Println(score, ok) //0,false false代表查询的键西门庄并不存在
/*
if ok == true 还可以写作 if ok
if ok == false 还可以写作 if !ok
*/
//if ok == true {
// fmt.Println("西门志的成绩是", score)
//} else {
// fmt.Println("查你妹,没有这个卵人")
//}
if score,ok := scoreMap["你妹"];ok {
fmt.Println("你妹的成绩是", score)
}else{
fmt.Println("没有你妹这个卵人")
}
}
/*复习数组和切片的遍历*/
func main053() {
//arr := [...]int{3, 1, 4, 1, 5}
slice := make([]int,5)
slice = append(slice, 1, 2, 3, 4, 5)
//同时遍历下标和对应的值
//for i,x := range slice{
// fmt.Println(i,x)
//}
//只遍历下标
for i := range slice{
fmt.Println(i)
}
}
/*map初始化时必须赋初始值,否则为nil-map(是不能添加键值对的)*/
func main054() {
//var tempMap map[string]float64//nil map 空映射,不能向其中添加键值
var tempMap map[string]float64 = map[string]float64{}//没有内容的map
fmt.Println("tempMap=",tempMap)
tempMap["你妹"]=666
fmt.Println("tempMap=",tempMap)
}
//遍历
func main055() {
scoreMap := make(map[string]int)
scoreMap["张全蛋"] = 59
scoreMap["穆铁柱"] = 63
scoreMap["张半蛋"] = 99
////遍历key和value
//for key, value := range scoreMap {
// //fmt.Printf("scoreMap[%s]=%d\n", key, value)
// fmt.Println(key,value)
//}
//遍历key
for key := range scoreMap {
fmt.Println(key,scoreMap[key])
}
}
标签:mpm end 分数 校验 ring false value 根据 长度
原文地址:https://www.cnblogs.com/yunweiqiang/p/11823778.html