2-19 map映射

map

 

func main() {
    //定义string为键int为值的map,用于存储分数
    //var score map[string]int = map[string]int{}
    //var score = map[string]int{}
    //score := map[string]int{}

    //没有指定长度,长度为0,一般不指定长度。
    scoreMap := make(map[string]int)
    //score := make(map[string]int,2)

    scoreMap["张全蛋"]= 59
    scoreMap["铁柱"]= 49
    scoreMap["张半蛋"]= 99

    //map的长度取决于键值的个数
    fmt.Printf("scoreMap的长度是%d\n",len(scoreMap))

    fmt.Println("张全蛋的成绩是,",scoreMap["张全蛋"])
    fmt.Println("铁柱成绩是,",scoreMap["铁柱"])
    fmt.Println("张半蛋的成绩是,",scoreMap["张半蛋"])

    scoreMap["张半蛋"] = 100
    fmt.Println("张半蛋的成绩是,",scoreMap["张半蛋"])
    fmt.Println("西门的成绩是,",scoreMap["西门"])
}

 

 

从上面的执行结果分析,map里面没有对应的键,值会返回0 

对map的结果进行校验。

    //固定写法,通过返回值判断
score, ok := scoreMap["张半蛋"] fmt.Println(score,ok) if ok ==true { fmt.Println("张半蛋的成绩是",score) }else { fmt.Println("没有这个人的成绩") } score ,ok = scoreMap["西门"] if ok == true{ fmt.Println("西门的成绩是",score) }else { fmt.Println("没有这个人的成绩") }

 

 执行结果

可以简写为

    if score ,ok  = scoreMap["西门"];ok == true{
        fmt.Println("西门的成绩是",score)
    }else {
        fmt.Println("没有这个人的成绩。")
    }
    
    if score ,ok  = scoreMap["西门"];ok {
        fmt.Println("西门的成绩是",score)
    }else {
        fmt.Println("没有这个人的成绩。")
    }

 

posted @ 2019-06-18 16:19  pad+  阅读(203)  评论(0编辑  收藏  举报