Go语言学习九:Map(集合)、递归函数、类型转换
2016-03-31 10:44
751 查看
// Map 是一种无序的键值对的集合。 // Map 最重要的一点是通过 key 来快速检索数据,key 类似于索引,指向数据的值。 // Map 是一种集合,所以我们可以像迭代数组和切片那样迭代它。 // 不过,Map 是无序的,我们无法决定它的返回顺序,这是因为 Map 是使用 hash 表来实现的。 package main import "fmt" // 递归函数 func Factorial(x int) (result int) { if x == 0 { //这里是从0一直return到设置的数字,然后再返回, result = 1 } else { result = x * Factorial(x-1) } return result } func main() { var countryCapitalMap map[string]string //定义集合,初始为nil countryCapitalMap = make(map[string]string) // 插入键值对 countryCapitalMap["France"] = "Paris" countryCapitalMap["Italy"] = "Rome" countryCapitalMap["China"] = "Paking" for country := range countryCapitalMap { //这里country如果是键,就不用加占位符,默认是第一个 fmt.Println("Capital of", country, "is", countryCapitalMap[country]) } captial, ok := countryCapitalMap["United States"] //这里的ok是看是否存在的,前面那个才是去键值对的、 if ok { fmt.Println("Capital of United States is", captial) fmt.Println(ok) } else { fmt.Println("Capital of United States is not present") fmt.Println(ok) } //删除集合元素 delete(countryCapitalMap, "France") for country := range countryCapitalMap { fmt.Println("Capital of", country, "is", countryCapitalMap[country]) } // 递归函数 var i int = 5 //数字不能太大,否则会超过int的界限 fmt.Println(i, "的阶乘是", Factorial(i)) //类型转换 var sum int = 17 var count int = 5 var mean float32 mean = float32(sum) / float32(count) fmt.Println("mean的值为", mean) }
相关文章推荐
- 转EGO 因地制宜选择合适的管理风格
- cross compile go
- Go语言学习八:切片(slice)和范围(range)
- 《How to Generate a Good Word Embedding?》导读
- 什么棋AlphaGo永远赢不了人类
- Django中的CSRF
- VIEWGOOD(远古)政企行业会议高清直播系统介绍
- Django 操作笔记
- VK Cup 2016 - Round 1 (Div. 2 Edition) C. Bear and Forgotten Tree 3 构造
- Go语言学习七:结构体
- VK Cup 2016 - Round 1 (Div. 2 Edition)C. Bear and Forgotten Tree 3(构造)
- Codeforces--368C--Sereja and Algorithm(规律)
- 106 miles to Chicago---zoj2797(最短路问题,求概率,模板)
- Go语言学习六:指针与传递到函数的指针
- CF_5A_ChatServer'sOutgoingTraffic
- 尽量用goto代替尾递归
- HZNU-1480-The Gougu Theorem【勾股数】
- Django基础——Model篇(二)
- Django创建工程及应用
- UVa11090 Going in Cycle!!