go map定义

go语言中map

map相当于python的字典,是key和value的一种集合

map声明方式

var map_test map[keytype]valuetype
example:
var user map[string]string

example 1

package main

import "fmt"

func main() {
     
	

	mes := map[string]int{
     
		"zhangsan":    11,
		"lisi":    12,
		"wangwu": 13,
	  }
	  name := "zhangsan"
	  v, ok := mes[name]
	  if ok {
     
		fmt.Printf("The user mes %q: %d\n", name, v)
	  } else {
     
		fmt.Println("fail")
	  }

}

输出

The user mes "zhangsan": 11
Process exiting with code: 0

example2

package main

import (
	"fmt"

)


func main() {
      
	user := make(map[string]string)
	user["zhangsan"] = "工程师"
	fmt.Println(user)
}

输出

`map[zhangsan:工程师]
Process exiting with code: 0`

make和new声明map的区别

在go语言中make和new都是创建map类型的方法,但是make对应的直接是实体,而new对应的则是一个指针,new方法创建的map是需要初始化后才可以被引用。

example3

package main

import (
	"fmt"
)


func main() {
      
	user := make(map[string]string)
	user["zhangsan"] = "工程师"
	fmt.Println(user)
	house := new(map[string]string) //使用new创建一个map指针
	*house = map[string]string{
     }
	(*house)["四合院"] = "beijing"
	fmt.Println(*house)
}

输出

map[zhangsan:工程师]
map[四合院:beijing]
Process exiting with code: 0

你可能感兴趣的:(go map定义)