map的三种声明定义方式
声明map后,一定要make开辟空间,否则会报越界且不能使用
package mainimport "fmt"func main() {// 第一种声明方式// 声明myMap1是一种map类型 key是string value是stringvar myMap1 map[string]string// 判断一下map在未开辟空间之前是否为空if myMap1 == nil {fmt.Println("myMap1是一个空map")}// 通过make关键字来给map开辟空间myMap1 = make(map[string]string, 10)myMap1["one"] = "java";myMap1["two"] = "c++";myMap1["three"] = "go";fmt.Println(myMap1)// 第二种声明方式-常用方式myMap2 := make(map[int]string)myMap2[1] = "java"myMap2[2] = "go"myMap2[3] = "py"fmt.Println(myMap2)// 第三种声明方式myMap3 := map[string]string{"one":"php","two":"c++","three":"java",}fmt.Println(myMap3)
}
map的使用方式
package mainimport "fmt"// 打印map集合
func printMap(cityMap map[string]string) {for key, value := range cityMap {fmt.Print("key:", key)fmt.Println(" value:", value)}
}// 更改map指定key的值
func changeMapValue(cityMap map[string]string) {cityMap["Japan"] = "Tokyoooooo"
}// 增加map
func addMapValue(cityMap map[string]string, key string, vale string) {if len(key) > 0 && len(vale) > 0 {cityMap[key] = vale}
}// 拷贝一个map
func copyMap(cityMap map[string]string) (map[string]string) {newMap := make(map[string]string)for key, value := range cityMap {newMap[key] = value}return newMap
}func main() {// 定义一个map,开辟空间cityMap := make(map[string]string)// 给map添加数据cityMap["China"] = "BeiJing"cityMap["Japan"] = "Tokyo"cityMap["USA"] = "NewYork"printMap(cityMap)fmt.Println("==========init===========")// 删除delete(cityMap, "USA")printMap(cityMap)fmt.Println("==========delete===========")// 修改changeMapValue(cityMap)printMap(cityMap)fmt.Println("==========update===========")// 添加addMapValue(cityMap, "张三", "zhangsan")printMap(cityMap)fmt.Println("==========add===========")// 拷贝一个mapreturnCopyMap := copyMap(cityMap)printMap(returnCopyMap)fmt.Println("=========copy============")
}
struct基本定义与使用
package mainimport "fmt"// 声明一种新的数据类型,是int的一个别名
type myint int// 定义一个结构体
type Book struct {title stringauth stringprice int
}// 传递一个book的副本,更改价格,打印不会生效,因为传递的是副本
func changeBook(book Book) {// 传递副本book.price = 55
}// 传递一个book的指针,更改价格,打印会生效,因为传递的是地址
func changeBook2(book *Book) {// 传递指针book.price = 55
}func main() {/*var a myint = 10fmt.Println("a = ", a)fmt.Printf("type of a = %T \n", a)*/var book Bookbook.title = "GO入门到放弃"book.auth = "自学"book.price = 100fmt.Printf("%v\n", book)fmt.Println("==========init===========")changeBook(book)fmt.Printf("%v\n", book)fmt.Println("==========副本update===========")changeBook2(&book)fmt.Printf("%v\n", book)fmt.Println("==========指针update2===========")
}