向map(映射)中添加新项的语法与数组相同。下面的程序将一些新项目添加到personSalary
map中。
package main
import (
"fmt"
)
func main() {
personSalary := make(map[string]int)
personSalary["steve"] = 12000
personSalary["jamie"] = 15000
personSalary["mike"] = 9000
fmt.Println("personSalary map contents:", personSalary)
}
输出: personSalary map contents: map[steve:12000 jamie:15000 mike:9000]
也可以在声明过程中初始化映射。
package main
import (
"fmt"
)
func main() {
personSalary := map[string]int {
"steve": 12000,
"jamie": 15000,
}
personSalary["mike"] = 9000
fmt.Println("personSalary map contents:", personSalary)
}
上面的程序声明了personSalary
,并在声明过程中添加了两个元素。稍后,添加了一个带有键mike
的元素。
程序输出
personSalary map contents: map[steve:12000 jamie:15000 mike:9000]
没有必要只使用字符串类型作为键。所有可以比较的类型,如布尔型、整数型、浮点型、复杂型、字符串型……也可以作为键。